Is Log4j isDebugEnabled() necessary before using logger.debug()?
java, log4j
Solution
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.
if(logger.isDebugEnabled()) {
logger.debug("The meaning of life is " + calculateMeaningOfLife());
}
IMO this makes the code a lot less readable so it should only be used when there's a significant performance improvement.
Edit 10 years after the original answer:
Now that we have lambdas, loggers have added support for suppliers that are only called when necessary. So the above code could be simplified to:
logger.debug("The meaning of life is {}", () -> calculateMeaningOfLife());
And the logger will only call `calculateMeaningOfLife()` if the message should be logged.
Problem
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())`??