Optimizing your Java logging

I have seen this in a lot of code and I figure I would blog about it because I think there is a lot of confusion around the best practices with regards to JSR47 and how to properly optimize your logging code. The first thing to remember is that methods like logger.fine(), logger.enter(), etc all do a log level check inside of the method and will ultimately not log unless the level is met. However, for optimization and CPU cycles you also need to be careful calling these methods with large strings or a large concatenation of strings.

Here is some sample code:

if (error > 0){

String myMessage = “Error: syncNow(): code= “;
myMessage += getErrorCode()
myMessage += ” because the server could not be found. Server = “;
myMessage += getServerName();

logger.fine(myMessage);

}

So now, any time there is an error all of that string concatenation will happen and the problem is the JVM may only be logging WARNINGS. The string building code is all for nothing, not to mention a call to those two methods plus the logger.fine() call. ie. You should also use a StringBuffer…

Some better code:

if (error>0 && logger.isLoggable(Level.FINE) ){

String myMessage = “Error: syncNow(): code= “;
myMessage += getErrorCode()
myMessage += ” because the server could not be found. Server = “;
myMessage += getServerName();

logger.fine(myMessage);

}

To summarize, it is ok to call logging methods with small and preferably static strings, ie “logger.fine(“My message”);” but you need to be careful in how much processing you do to get that string.

Java Logger Class
Java Logging Overview

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.