如何用 SLF4J 占位符记录异常和消息

使用 SLF4J记录错误消息和异常的正确方法是什么?

我试过这样做,但是异常堆栈跟踪从未打印出来:

logger.error("Unable to parse data {}", inputMessage, e);

在这种情况下,我想用 inputMessage填充 {},并注销异常堆栈跟踪。

我能想到的唯一办法就是这么做:

logger.error("Unable to parse data " + inputMessage, e);

这可不好看。

58845 次浏览

As of SLF4J version 1.6, SLF4J will interpret the last parameter as you intended, i.e. as an exception. You must be using an older version of SLF4J API.

This feature is documented in a faq entry which is also referenced in the javadocs for Logger.

from http://www.slf4j.org/faq.html#paramException:

Yes, as of SLF4J 1.6.0, but not in previous versions. The SLF4J API supports parametrization in the presence of an exception, assuming the exception is the last parameter. Thus,

String s = "Hello world";
try {
Integer i = Integer.valueOf(s);
} catch (NumberFormatException e) {
logger.error("Failed to format {}", s, e);
}

will print the NumberFormatException with its stack trace as expected. The java compiler will invoke the error method taking a String and two Object arguments. SLF4J, in accordance with the programmer's most probable intention, will interpret NumberFormatException instance as a throwable instead of an unused Object parameter. In SLF4J versions prior to 1.6.0, the NumberFormatException instance was simply ignored.

If the exception is not the last argument, it will be treated as a plain object and its stack trace will NOT be printed. However, such situations should not occur in practice.