Learner
Learner

Reputation: 1523

slf4j logging - difference between the two error logging methods (with and w/o Throwable)

I am using slf4j 1.7.x for logging in our Java project. The Logger interface has multiple methods to log at ERROR level such as these two:

void error​(String msg, Throwable t)
void error​(String format, Object... arguments)

My question is, if I would like to log an exception in my catch block which of these two is considered better and what information is logged in which one, if I have it as follows?

try {
    // Code to call sdk for ABC Service
} catch (AbcServiceException | CredentialException | IOException e) {
    logger.error("Error during getting information from Abc", e);
    //OR
    logger.error("Error during getting information from Abc {} {} ", e.getMessage(), e.getCause());

    return null; // Or return some default value
}

Upvotes: 2

Views: 2131

Answers (1)

Adam Kotwasinski
Adam Kotwasinski

Reputation: 4574

It's an opinionated answer, but I prefer the throwable-consuming APIs, as it provides multi-level stack trace and appears to be the most used API in projects.

Also remember that slf4j 1.6 or later can detect if last param in Object[] is an exception, it's easy to have parameterized logging with exceptions too - see http://www.slf4j.org/faq.html#paramException for an example.

In the end, just writing LOG.error("blah blah {} {}", arg1, arg2, exception) has worked fine for me.

Upvotes: 2

Related Questions