Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Log4j isDebugEnabled() necessary before using logger.debug()? [duplicate]

Tags:

java

log4j

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())??

like image 798
prasanth Avatar asked Jul 25 '13 06:07

prasanth


People also ask

Do we need isDebugEnabled?

It's use is optional since it is called by the log method internally.

How do I enable DEBUG mode in log4j?

You need to set the logger level to the lowest you want to display. For example, if you want to display DEBUG messages, you need to set the logger level to DEBUG. The Apache log4j manual has a section on Configuration.

What is isDebugEnabled?

The guard statement (checking isDebugEnabled() ) is there to prevent potentially expensive computation of the log message when it involves invocation of the toString() methods of various objects and concatenating the results.

What is difference between DEBUG and info in log4j?

INFO is used to log the information your program is working as expected. DEBUG is used to find the reason in case your program is not working as expected or an exception has occurred. it's in the interest of the developer.


1 Answers

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.

like image 172
Guillaume Avatar answered Oct 11 '22 10:10

Guillaume