Even with slf4j, should you guard your logging?

The slf4j site, indicates that because of the parameterized logging, logging guards are not necessary.

I.e. instead of writing:

if(logger.isDebugEnabled()) {    
    logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
}

You can write:

Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

The improvement that slf4j did was that you could pass objects that get inserted into a string by calling toString() only when needed. This optimizes performance when that particular logging operation is disabled. Check the complete source.

private void formatAndLog(int level, String format, Object arg1, Object arg2) {
    if (!isLevelEnabled(level)) {
        return;
    }
    FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
    log(level, tp.getMessage(), tp.getThrowable());
}

But, does this means logging guard is useless? Short answers is no.

Logging guard should be use when an expensive operation needs to be log. Let’s say we have the next class:

public class Example {
    Logger logger = LoggerFactory.getLogger(Example.class);
    public String doSomeExpensiveOperation() {
        logger.info("Hello, I'm always called if I'm not guarded");
        return "This is my result";
    }
}

If we execute the code without doing logging guard

logger.debug("Operation {} ", example.doSomeExpensiveOperation());

Output:

[main] INFO log.guard.Example - Hello, I'm always called if I'm not guarded
Process finished with exit code 0

We pay the example.doSomeExpensiveOperation()

We save the "Operation: {} ", + obj.toString()

The doSomeExpensiveOperation is always executed because Java doesn’t treats methods as first class citizens.

But if we do logging guard we could save the doSomeExpensiveOperation.

if (logger.isDebugEnabled()) {
    logger.debug("Operation {} ", example.doSomeExpensiveOperation())
}
Output:
 
Process finished with exit code 0

We pay the logger.isDebugEnabled()

We save the example.doSomeExpensiveOperation()

We save the "Operation: {} ", + obj.toString()

In conclusion, logging guard is not useless. I’m not trying to enforce good/bad practices. Some people prefer having less verbose code rather than saving performance in expensive operations. But, by really understanding how slf4j works, you could analyze and determine which way suits you best!

Tags: 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

PHP code

  • You may post PHP code. You should include <?php ?> tags.