Skip to content
Advertisement

Substituting parameters in log message and add a Throwable in Log4j 2

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

Advertisement

Answer

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