Substituting parameters in log message and add a Throwable in Log4j 2
Asked Answered
Z

2

56

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);
Zygospore answered 30/1, 2016 at 0:59 Comment(0)
S
23

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);
Saucepan answered 30/1, 2016 at 1:45 Comment(1)
In case anyone is wondering, the above would be expressed as: logger.error(new ParameterizedMessage("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()), exception);Height
R
103

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

Rammer answered 10/8, 2018 at 8:2 Comment(1)
The Log4j 2 behavior is mentioned at logging.apache.org/log4j/2.x/manual/…: "Additionally, you can pass a Throwable as the very last parameter. There's no need to add an extra substituting parameter in this case as it will be handled by the logging API automatically."Consummate
S
23

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);
Saucepan answered 30/1, 2016 at 1:45 Comment(1)
In case anyone is wondering, the above would be expressed as: logger.error(new ParameterizedMessage("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()), exception);Height

© 2022 - 2024 — McMap. All rights reserved.