Jin Kwon
Jin Kwon

Reputation: 21978

How to log with format, arguments, and thrown?

In Logger, I think I can't find any method for reporting with a formatted message and a throwable.

I found

error(String format, Object... arguments) 
error(String msg, Throwable t) 
try {
    doSomething(arg1, arg2);
} catch (final SomeException se) {
    logger.error("Failed to do something with {} and {}", arg1, arg2);
    logger.error("Failed to do something", se);
}

Is there any way to do like this?

logger.error("Failed to do something with {} and {}", new Object[]{arg1, arg2}, se);

Upvotes: 2

Views: 124

Answers (1)

Tomas Karban
Tomas Karban

Reputation: 1174

Don't be afraid, just do it! SLF4J is smart enough. If you provide more arguments than placeholders, the logger will attempt to cast the last argument to Throwable. If it succeeds, then you get a nice stack trace in the log. This feature was introduced in SLF4J version 1.6.0 -- see http://www.slf4j.org/news.html and also http://www.slf4j.org/faq.html#paramException.

Usage like the following works fine:

logger.error("one {} two {} error", new Object[] { 1, 2, new RuntimeException("stack trace") });

Starting with version 1.7.0 there are new varargs overloads, so you can simply use

logger.error("one {} two {} error", 1, 2, new RuntimeException("stack trace"));

Upvotes: 4

Related Questions