2

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);

1 Answer 1

4

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.