Reputation: 13321
I am trying to log an exception, and would like to include another variable's value in the log message. Is there a Logger API that does this?
logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);
Upvotes: 57
Views: 45090
Reputation: 3631
Have you tried looking at ParameterizedMessage?
From the docs
Parameters:
messagePattern - The message "format" string. This will be a String containing "{}" placeholders where parameters should be substituted.
objectArgs - The arguments for substitution.
throwable - A Throwable
e.g.
logger.error(new ParameterizedMessage("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()), exception);
Upvotes: 23
Reputation: 1471
There is an undocumented feature in Log4j 2 (and SLF4J 1.6+).
One can pass Throwable
as the very last parameter. And it would then get a special treatment.
See AbstractLogger#logMessage(String, Level, Marker, String, Object...)
and ReusableParameterizedMessage#initThrowable()
.
There is no need to bother with ParametrizedMessage
. The code in the question will work just as expected:
logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);
Upvotes: 105