Skip to main content

Posts

Showing posts from December, 2009

Logging needs some lazy evaluation

If it's one situation where lazy evaluation is needed in Java, it's logging. Until something better comes up and we'll have logging injected via AOP or something similar, a log message will be just the result of an extra line in our Java files, and this is a problem.
A normal log message is something like this:
log.fine("Some parameter is:" + someVariable);
This looks quite harmless especially since we know that depending on the log level, our message might be saved or not.
But say we have an expensive function:
log.fine("The extra informations starts at" + reallyLongLastingFunction());
The problem above is obvious: the log string will be built no matter what and our reallyLongLastingFunction() will be called each time, including when the log won't actually be saved.
The solution to this is to pollute your code with something like:
if(log.isLoggable(Level.FINE)){ log.fine("The extra informations starts at" + reallyLongLastingFunction()); }
This way…