Showing posts with label Logging. Show all posts
Showing posts with label Logging. Show all posts

Friday, May 18, 2007

When to call isDebugEnabled() before writing debug messages

When using a logging framework like log4j most developers never check whether debug is enabled before writing a debug message or always makes the check. The theory behind it is to prevent unnecessary string concatenations if debug messages are disabled, which is the case most of the times on production environments.

logger.debug("Saved order successfully. Order ID : " + order.getId() +
" items in order " + order.getItems().size())
;

In the above case there is a new string object created by concatenating all the parameters before making the call to debug method. This is done regardless of debug is enabled or not which will be a unnecessary performance overhead if debug is disabled.

if( logger.isDebugEnabled()){
logger.debug("Before saving the order");
}

In the above code section the if condition is not necessary as there is no String concatenations involved and ends up adding two redundant lines of code.

Therefore the rule would be to do a isDebugEnabled check only if there is any String concatenation involved in the call to debug. This seems to be obvious but developers somehow keep getting this wrong.

Don' forget to click the +1 button below if this post was helpful.

Reduce logger initialization code in your Java applications

You might have logger initialization code in most of the classes in an application (e.g. Action, Service and DAO classes). This is actually unnecessary if these types of classes extend from your own base classes.

An application using log4j logging framework will initialize the logger in a class as

private static final Logger logger = Logger.getInstance(TestAction.getClass());

This is done in each and every class which needs to use a logger. Now if we use a base class for lets say all Struts Actions called BaseAction, it can contain the logger initialization code as below.

package com.test.web;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;

public abstract class BaseAction extends Action{
//initializes the logger object
protected final Logger logger = Logger.getInstance(this.getClass());
}


Now all sub classes that extends from BaseAction (implementation action classes) will have the logger object created on initialization with the proper class name. Even though in theory this creates a new logger object per instance of TestAction class, it wont be an issue since Struts will maintain only a single instance of TestAction to serve all requests mapped to it.

This could be applied to all Service, DAO classes as well if you are using a framework like Spring to manage them, where only one instance per implementation class will be created.

P.S. This post was modified as per comments by fabien...

Don' forget to click the +1 button below if this post was helpful.