As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
{}
more, the matter of taste... – BetlistatoString()
method of the arguments might be expensive. With this syntax, only a reference to each object is passed and thetoString()
method is only called if the particular message is actually getting logged. Objects referenced in aninfo()
log call will not have theirtoString()
method called if the log level isWARN
or higher. The{}
syntax is a reminder to users that this is not aString.format()
-like operation, i.e. they should pass objects rather than string representations thereof. – user149408