Logging with log4J isDebugEnabled

Alot of times I have seen the questions popping up whether to use isDebugEnabled property or not. Arguably most of the times or rather always about performance. Some of the stuff that I feel important about using it follows.

The answer is simple. It is made to be used. However using it has to be with caution.

For instance
If I am using the following line in my code.

  1. log.debug("I am there");

Thats an example of a good practise

However I can really blow it out of proportions if I do the following.

  1. // Not good practise
  2. if (log.isDebugEnabled()){
  3.     log.debug("I am there"); 
  4. }

And why exactly is that so. This is because the method debug in the class Category i.e. extended by Logger in the log4j libraries explicitly checks the mode for the logging itself.

Extract from the class org.apache.log4j.Category is below

  1. public void debug(Object message) {
  2. if(repository.isDisabled(Level.DEBUG_INT))
  3. return;
  4. if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) {
  5. forcedLog(FQCN, Level.DEBUG, message, null);
  6. }
  7. }

Okay so thats the case where we say dont use it. What about the one where we actually do use the isDebugEnabled property.

For instance you have a large parameter going in the debug.

  1. // Bad Practise
  2.  log.debug("XML "+Tree.getXMLText());

In such a case it can clearly be said “No dont do it!” If Tree.getXMLText is going to pull out all the hair out of the app then there is no use. As it will be constructed first and if the debug level is not enabled that would be a performance cost.

  1. // Good Practise
  2. if (log.isDebugEnabled()){
  3.     log.debug("XML "+Tree.getXMLText());
  4. }

Thus in the example above it would be wiser to use log.isDebugEnabled() just to make sure the mileage or cost stays lesser.