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..?
Conclusion. So essentially, SLF4J does not replace Log4j, Both work together. SLF4j removes the tight coupling between the application and logging frameworks. It makes it easy to replace with any other logging framework in the future with a more capable library.
Comparison SLF4J and Log4j Unlike log4j, SLF4J (Simple Logging Facade for Java) is not an implementation of logging framework, it is an abstraction for all those logging frameworks in Java similar to log4J. Therefore, you cannot compare both. However, it is always difficult to prefer one between the two.
In fact, it is not possible to guarantee that a Logger will always be thread-safe. Someone could implement their own slf4j compatible logging classes. Such an implementation could be non-thread-safe, by accident or by design. If it was, then the Logger exposed via the slf4j facade would also be non-thread-safe.
slf4j. simpleLogger. defaultLogLevel - Default log level for all instances of SimpleLogger. Must be one of ("trace", "debug", "info", "warn", "error" or "off").
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());
obj = getUserService().getCurrentUser()
"User name: " + obj.toString()
If we use logging guard:
if (logger.isDebugEnabled()) { logger.debug("User: {}", getUserService().getCurrentUser()); }
logger.isDebugEnabled()
obj = getUserService().getCurrentUser()
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With