Wednesday, June 17, 2009

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.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home