How and when and what to log ?

Sahil Aggarwal
3 min readApr 22, 2021

We as a developers understand the importance of coding but most of us do not know the right way to log.

While seeing others code you must have seen various patterns of logging:

  • Log everything

on start of any function call

on every function call

before every return statement

  • Don’t log anything
  • Log only Exceptions

I think everybody must have seen all type of developers, lets understand when to log and also in diff. scenarios , but before that first see the purpose of logging:

Purpose of Logging

  • Provides insights about the flow of your code, what happen , what are the parameters which were passed
  • You could virtually run the entire flow of your code and understand the problems while debugging any unexpected behavior in your code.

Lets go scenario by scenario

In the following i want you see the reasoning to when to log that may help you to decide in your scenarios.

General Recommendation

  • Now if you are writing pure functions (not using global variables, not modifying any variable provided) then mostly you would not require to log any thing in those functions(will be writing a blog on the pure functions), as you could drive most of the things from the input.
  • If any specific decision that will completely change the flow of the code , we should generally log the decision and reason in info
  • Log any exception which happens in to the system with type error
  • any parameter you are reading from system , generally log this with fine as you can cross check this , do not just log , not a hardline if some function is called limited number of times

Http Service Call / Any third party Call

  • parameters which are passed to it log using info, always check whether in your environment it is already done by framework library code (like in rest filters , tomcat logs) then do not log, generally its a good practice to handle this at framework level rather than everybody taking care of this

Timer or Scheduler Jobs

  • In case of timer first thing is , if timer is every some seconds log the time in which it started

Service to Service(within same process, Spring Services) Calls

  • When service call to another service the calling service should not log generally assuming the responsibility is with the called service. rest remain same as above in http one

DB Queries

  • before calling a query we should generally log with info the parameters we are passing

Now when to log fine

  • Generally anytime when there are decisions taken in the code one can log on fine. The configurations read by the system we can log with fine, Some internal data structures created or modified or any lifecycle event like DB connection closed we can log such things with fine. But do not add lots and lots of log , it can kill your system as described in link .

Originally published at http://hello-worlds.in on April 22, 2021.

--

--