There is no magic in slf4j. The problem with logging used to be that if you wanted to log let's say
logger.debug("expensive string representation: " + godObject)
then no matter if the debug level was enabled in the logger or not, you always evaluated godObject.toString()
which can be an expensive operation, and then also string concatenation. This comes simply from the fact that in Java (and most languages) arguments are evaluated before they're passed to a function.
That's why slf4j introduced logger.debug(String msg, Object arg)
(and other variants for more arguments). The whole idea is that you pass cheap arguments to the debug
function and it calls toString
on them and combines them into a message only if the debug level is on.
Note that by calling
logger.debug("expensive string representation, eg: {}", godObject.toString());
you drastically reduce this advantage, as this way you convert godObject
all the time, before you pass it to debug
, no matter what debug level is on. You should use only
logger.debug("expensive string representation, eg: {}", godObject);
However, this still isn't ideal. It only spares calling toString
and string concatenation. But if your logging message requires some other expensive processing to create the message, it won't help. Like if you need to call some expensiveMethod
to create the message:
logger.debug("expensive method, eg: {}",
godObject.expensiveMethod());
then expensiveMethod
is always evaluated before being passed to logger
. To make this work efficiently with slf4j, you still have to resort back to
if (logger.isDebugEnabled())
logger.debug("expensive method, eg: {}",
godObject.expensiveMethod());
Scala's call-by-name helps a lot in this matter, because it allows you to wrap arbitrary piece of code into a function object and evaluate that code only when needed. This is exactly what we need. Let's have a look at slf4s, for example. This library exposes methods like
def debug(msg: => String) { ... }
Why no arguments like in slf4j's Logger
? Because we don't need them any more. We can write just
logger.debug("expensive representation, eg: " +
godObject.expensiveMethod())
We don't pass a message and its arguments, we pass directly a piece of code that is evaluated to the message. But only if the logger decides to do so. If the debug level isn't on, nothing that's within logger.debug(...)
is ever evaluated, the whole thing is just skipped. Neither expensiveMethod
is called nor any toString
calls or string concatenation happen. So this approach is most general and most flexible. You can pass any expression that evaluates to a String
to debug
, no matter how complex it is.