Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
pjp Avatar asked May 10 '11 13:05

pjp


People also ask

How do you log error messages in Java?

We can display the Java error messages using the logger. error("Error Message") method.

Can slf4j work without log4j?

Conclusion. So essentially, SLF4J does not replace Log4j, Both work together. SLF4j removes the tight coupling between the application and logging frameworks. It makes it easy to replace with any other logging framework in the future with a more capable library.


1 Answers

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.

like image 59
Ceki Avatar answered Oct 14 '22 21:10

Ceki