slf4j vs log4j

Logging Comments

Any Java developer who has worked on production systems or applications would realize the importance of logging. And in Java, there are various logging tools - java.util.logging, log4j and slf4j. I’ve been using log4j for a while now but recently switched to slf4j and here’s why -

  1. slf4j is not an implementation but it is an abstraction layer. So, if you’re writing a library that would be passed around, you don’t want your library to be tied to a particular logging implementation - slf4j provides this abstraction.

  2. The other main reason for switching is the use of placeholders in slf4j. This is a commonly found code snippet if you’re using log4j,

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

In the above statement, both i and entry[i] are converted to Strings and then concatenated, irrespective of whether this statement is logged or not. This cost could be overcome by the use of an if statement -

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

The above code snippet will ensure that the string concatenation is not executed when the logging level is set to - say ERROR. However, there is always a conditional check (to check the logging level). Additionally, having a lot of these code snippets impacts the code readability. The problem is solved in slf4j by using placeholders -

logger.debug("Entry number {} is {}",i, entry[i]);

In the above statement, the string concatenation happens only when the logging level is set to DEBUG and also there are no conditional checks.

Kaushik Rangadurai

Code. Learn. Explore

Share this post

Comments