Search code examples
javaperformanceloggingslf4j

Even with slf4j, should you guard your logging?


Help me out in a debate here.. :)

The slf4j site here http://www.slf4j.org/faq.html#logging_performance 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 get away with:

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

Is this really okay, or does it incur the (albeit lower) cost of creating the static string that's passed to the trace method..?


Solution

  • I'll try to put my two cents from another perspective

    What is exactly the benefit of parametrized logging?

    You just defer toString() invocation and string concatenation until really needed, which is when you really have to log the message. This optimizes performance when that particular logging operation is disabled. Check source code for SLF4J if not sure.

    Does parametrized logging makes guards useless in all cases?

    No.

    In which cases would logging guards be of use?

    When there are other potential expensive operations.

    For example (in the case this particular logging operation is disabled), if we have no logging guard

    logger.debug("User name: {}", getUserService().getCurrentUser());
    
    1. We would pay the cost from obj = getUserService().getCurrentUser()
    2. We would save the cost from "User name: " + obj.toString()

    If we use logging guard:

    if (logger.isDebugEnabled()) {
        logger.debug("User: {}", getUserService().getCurrentUser());
    }
    
    1. We would pay the cost of logger.isDebugEnabled()
    2. We would save the cost from obj = getUserService().getCurrentUser()
    3. We would save the cost from "User name: " + obj.toString()

    In the later case, we would save both costs at the price of checking isDebugEnabled() twice when this particular logging operation is enabled.

    NOTE: This is just an example, not trying to debate good/bad practices here.