Sorting Logger with If clause to avoid redundant string construction

I got a recommendation to use this syntax when entering java:

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

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

I would like to hear what others are doing, or if you think this is necessary at all.

Thanks!!

+5
source share
4 answers

Some new logging frameworks allow you to specify arguments as parameters and will not evaluate them if there is no registration.

, , LogBack, Log4j. : http://www.infoq.com/news/2007/08/logback

, . , .


Log4j:

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

LogBack:

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

, LOGBack , . , .

+6

String , . , . , , , . .

: , , , ​​:

public static final boolean DEBUG = false;

if-, , JVM . #ifdef.

if (Globals.DEBUG) {
    // Logging call
}
0

. 10 , .

0

This is an improvement (good), but it can be improved a bit.

Set the final flags for each logging level (FINE, etc.) in the global object used as the configuration, then use StringBuffer to create your debug output - you can even format numbers into a stream at the same time.

public class MyAppConfig {
  public final boolean FINE=true;
  // ... other fields
}

public class MyApp {
  void someFunction() {
    ...
    int imagesProcessed;
    imagesProcessed = processImages();

    if (MyAppConfig.FINE) logger.fine(new StringBuffer(35).
      append("Count of images processed: ").append(imagesProcessed).toString());

    ...
  }
}

Here, the string buffer is configured with an "initial capacity" of 35 characters. If you know how many characters will be created, you can specify hints for StringBuffer.

0
source

All Articles