Even with slf4j, should you guard your logging?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)