简体   繁体   中英

How to log exception and message with placeholders with SLF4J

What's the correct approach to log both an error message and an exception using SLF4J ?

I've tried doing this but the exception stack trace is never printed:

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

In this case I want to populate {} with the inputMessage as well as logging out the exception stacktrace.

The only way I can see to do this would be to do this:

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

which is not pretty.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM