Often when use SLF4J, you may wonder if an exception object can be printed in the same parameterized log message together with other objects. Actually SLF4J supports it since 1.6.0.

log.error("failed to add item {}", "item-id-1", new RuntimeException("failed to add item"));

The SLF4J call above prints log message like below.

13:47:16.119 [main] ERROR example.TmpTest - failed to add item item-id-1
java.lang.RuntimeException: failed to add item
    at example.TmpTest.logErrorTest(TmpTest.java:10)
    ...
    ...

So it actually doesn’t need to log as below.

log.error("failed to add item {}", "item-id-1");
log.error("exception details:", new RuntimeException("failed to add item"));

Here is what the official FAQ says.

The SLF4J API supports parametrization in the presence of an exception, assuming the exception is the last parameter.

Use the first style to save one line.

SLF4J doesn’t clearly state this behavior in the Javadoc of Logger.error(String format, Object... arguments) (at least not in the 1.7.26 version). Maybe if a new method like below is added to Logger, programmer would find out this feature more easily.

public void error(String format, Throwable t, Object... arguments);