Are You Paying Unnecessary Logging Tax?

No, I don’t mean the forestry kind. I’m talking about programming and the generous amounts of information that developers often write out to an application’s log file in order to perform post mortem analyses. I have come across projects where logging has been a performance killer. Fortunately, it doesn’t have to be that way and I will show some common mistakes and how to fix them.

Parameters To a Method Call are Always Evaluated

I often see this kind of logging statement in Java code.

logger.debug("some highly informative message");

While you may not see any output in the log file when you set the logging level to INFO or above, the problem is that you’re still paying a runtime performance penalty because your string concatenation can be very expensive. Consider the following example:

logger.debug("paying" + " the" + " logging " + expensiveOperation.toString() + " tax.");

Java logging is quite efficient and the runtime cost is non-existent compared to the expensive set of string operations above. The string concatenation is performed before being passed to the logger’s debug() method, so whether or not it appears in the actual log file, you’ve incurred the logging tax.

A better way to write logging statements is to always wrap it in a code guard that checks to see if we’re in the appropriate log level.

if (logger.isDebugEnabled()) {
  logger.debug("paying" + " the" + " logging " + expensiveOperation.toString() + " tax.");

This can make a huge difference. So save on all those operations that are only meant to be written out to the log inside of the code guard.

Redundancy Redundancy is Wasteful Wasteful

Sometimes, logging messages are generated from multiple places that contain the exact same information. This can easily occur on projects where multiple developers are working on the same project/code base and want to see detailed info at various points. Consolidate all those messages if they must follow the same logical path. It will improve the performance as well as make it easier to search through the logs.

Consider Your Reader

What purpose does your message serve? Is it only meant for developers? Is it useful if there’s a problem in production? Do I really need to see the whole 40k of SOAP xml or just a portion of it? Be aware of the logging level and the detail level.


If you’re using Apache Commons Logging, have a look at their recommended best practices.

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply