Friday, 22 December 2017

Why use slf4j over log4j or logback for logging in Java


In last post we saw how we can use slf4j over log4j and logback -
 But the question is why would be use slf4j over any logging implementation and not use the actual implementation. In this post we will try to understand this question.

 SLF4J or Simple logging Facade is not really a logging implementation but an abstraction that can use any of the logging implementation like -
  • java.util.logging, 
  • Apache log4j, 
  • logback etc
So consider this - You have developed a project that uses log4j for logging. But your project is dependent on some other module/library that uses lets say logback for logging. In this case you will need to include logback jar in your application as well. This is just unnecessary overhead. If the module your project is dependent on used slf4j then it could have reused our existing log4j configurations and jar.

Other way to see this is let's say you are writing a library that you want someone else to use. In this case you can use slf4j and let the user of your library choose the actual logging implementation rather than using a actual logging implementation like log4j and  making the user of your library stick to the same.

In short slf4j makes your code independent of any logging implementation specially if your code is part of public api/library.

Now that we know the very basics of why one would use slf4j lets see some of it's advantages -

Why use slf4j over log4j or logback for logging in Java

Let us see how a log statement would look in a log4j implementation -

if (logger.isDebugEnabled()) {
    logger.debug("Inputs are input1 : " + input1 + " input2 : " + input2 );

Couple of quick observations -
  1. Lot of boiler plate. Need to check if debug level is enabled everytime we need to log a debug statement.
  2. Lot of string concatenation everytime we call this debug statement.
In slf4j it would be as simple as -

logger.debug("Inputs are input1 : {} , input2 : {}" , input1, input2 );

Here {} are the palceholders and are replaced by the comma separated arguments provided later in the call. Yes the method takes variable arguments. And this is cool because - No more string concatenations!

You also avoid the boiler plate code since sl4fj will internally take care of the logging levels and proceed only if debug level is enabled. So if debug is not enabled final string needed to be logged is not even created. This not only help save memory but also CPU.

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top