Robin Bajaj
Robin Bajaj

Reputation: 2072

java util logging calls methods even when log levels don't allow them

If I have a java util logging statement such as

logger.log(LEVEL.FINE, "data buffer = {0}", 
CommonUtils.prepareDataBufferString(dataBuffer));

Now even when my log level is not at FINE, the expensive prepare.. method still gets called, which is not what I want to happen. I end up checking the logger level before this statement

if(logger.isLoggable(LEVEL.FINE)){
   bufferString = CommonUtils.prepareDataBufferString(dataBuffer);
}

logger.log(LEVEL.FINE, "data buffer = {0}", bufferString);

this increases the lines of code unnecessarily. Can I avoid having to do this somehow. please help.

Upvotes: 2

Views: 299

Answers (2)

sjr
sjr

Reputation: 9875

A technique like this might help.

logger.log(LEVEL.FINE, "data buffer = {0}", 
    new Object() {
        @Override public String toString() {
            return CommonUtils.prepareDataBufferString(dataBuffer));
        }
    });

FYI, it's not the log framework calling the method, it's Java. Java requires that you evaluate all the parameters to a method before the method can be invoked (this is called eager evaluation, contrast to lazy evaluation).

Upvotes: 4

bmargulies
bmargulies

Reputation: 100042

No you can't avoid it with any Java logging API that I know. There are really only two ways in the language to do what you want:

  1. the if statement that you describe
  2. passing an object that implements an interface into the API to produce the details.

No logging API that I know implements (2), and I'm not sure that you'd find it less verbose to pass in an anonymous object.

Upvotes: 2

Related Questions