Search This Blog

Saturday, February 21, 2015

SL4J and parameterized messages

It's common to log messages that contain run-time information. In Java, this is easier if you use SL4J instead of log4j.


Here's a useful snippet from http://javarevisited.blogspot.com/2013/08/why-use-sl4j-over-log4j-for-logging-in.html

This is how you would do in Log4j, but surely this is not fun and reduce readability of code by adding unnecessary boiler-plate code.


if (logger.isDebugEnabled()) {
    logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
}


On the other hand if you use SLF4J, you can get same result in more concise format as shown below:


logger.debug("Processing trade with id: {} and symbol : {} ", id, symbol);


In SLF4J, we don't need String concatenation and don't incur cost of temporary not need String. Instead, we write log message in a template format with placeholder and supply actual value as parameters.



Post a Comment