Background
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
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 -
- Lot of boiler plate. Need to check if debug level is enabled everytime we need to log a debug statement.
- Lot of string concatenation everytime we call this debug statement.
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.