This question already has an answer here:
When I was going through some code, I noticed the use of logger as follows,
if(logger.isDebugEnabled())
logger.debug("Something..");
But in some codes, I observed like this.
logger.debug("Something..");
When I looked at the source of log4j, in the debug()
method of Logger itself if(logger.isDebugEnabled())
was checked. Then why do we need this unnecessary overhead if(logger.isDebugEnabled())
??
Java must first resolve the string parameter passed to the debug method before it can call it.
The above code will result in multiple String objects being created as each + creates another String so you'll have about 5 or more objects created before calling the method.
Debugging will mostly not be enabled so it's more efficient to check if debugging is enabled than to resolve the parameters all the time.
The statement:
Is used just for performance reasons. It's use is optional since it is called by the log method internally.
But now you ask if this check is made internally, so why should I use it? It's very simple: if you log something as simple as this:
Then you don't need to do any check. If you compose a string to log using the append operator (+) like this:
In this case you should check if the log is enabled or not, because if it isn't, even if the log is not made, the string composition is. And I must remind you that the use of operator "+" to concatenate strings is very inefficient.
SLF4J implementation (checked on version 1.7.10) calls
isDebugEnabled()
in some methods like:but there are also method overloads which doesn't internally check whether given loggin level is enabled, like in:
Another thing is that Logger implementation can be changed so if you want to be always sure your logger is called according to it's logging level, then you might want to consider using
isDebugEnabled()
method.It's useful when the String your passing to
logger.debug(...)
takes time to evaluate, in that case you can skip this evaluation if debug is not enabled.IMO this makes the code a lot less readable so it should only be used when there's a significant performance improvement.
isDebugEnabled is typically used to avoid unnecessary String concatination, eg this call
first invokes Strings concatination then debug() and only then Logger detects that debug is not enabled and simply returns. This may significantly affect app performance.
This problem is solved in SLF4J which has formatted logging methods like this