2

I am doing a code review and I would like your thought about a small piece of code:

if(logger.isDebugEnabled())
{
    logger.debug("debug log");
} 

Is there a real reason/benefit of doing the test if(logger.isDebugEnabled()) ?

Why not just write logger.debug("debug log"); without the test ?

TheEwook
  • 11,037
  • 6
  • 36
  • 55
  • 5
    Did you try to look for it before asking? http://stackoverflow.com/questions/963492/in-log4j-does-checking-isdebugenabled-before-logging-improve-performance – BobTheBuilder Apr 04 '13 at 11:23
  • @baraky Yes it's exactly what I am looking for. Thanks for the link (didn't find it before posting my question) – TheEwook Apr 04 '13 at 11:26

1 Answers1

6

It is not useful for the example that you provided. But it can be useful if you include other data in the log line, for example:

logger.debug("Info: " + someObject.getSomeInformation());

Note that the method getSomeInformation will be called on someObject before logger.debug is called, whether the level is debug or not. Also, a string concatenation will be performed. To avoid the cost of the method call and string concatenation, you can put this in an if like in your question.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • `Note that the method getSomeInformation will be called on someObject before logger.debug` I didn't know about that. Indeed now I can see the difference. Thanks for your insight ;) – TheEwook Apr 04 '13 at 11:28