Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorrounding Logger with an If clause to avoid redundant String construction

Tags:

java

logging

I got a recommendation to use this syntax when logging in java:

if (logger.isLoggable(Log.FINE))
{
    logger.fine("bla"+" bla"+" bla");
}

The reason for this is to avoid the redundant construction of the parameter string incase the logging level is lower than "FINE". (in the example above - 5 redundant string object. (" bla"X3, " bla bla" and "bla bla bla").

I'd like to hear what others are doing about this or if you think that this is necessary at all.

Thanks!!

like image 836
Ben Avatar asked Jan 10 '10 16:01

Ben


1 Answers

Some newer logging frameworks allow you to specify arguments as parameters, and won't evaluate them if there's no logging.

The example I found is LogBack, the successor to Log4j. Here's the info: http://www.infoq.com/news/2007/08/logback

This gives you the best of both worlds, so to speak. Elegant syntax yet good performance.


Log4j code example:

if( logger.isDebugEnabled() ) {
  logger.debug( "User with account " + 
    user.getAccount() + " failed authentication; " +
    "supplied crypted password " + user.crypt(password) +
    " does not match." );
}

Equivalent LogBack code:

logger.debug( "User with account {} failed authentication; " +
    "supplied crypted password {} does not match.",
    user.getAccount(), user.crypt(password) );

This defers the cost of message assembly until LOGBack has ascertained whether or not this message will be viewed. It doesn't defer the cost of retrieving expensive parameters, such as the password crypting in the above example.

like image 165
Carl Smotricz Avatar answered Oct 19 '22 10:10

Carl Smotricz