替换日志消息中的参数并在 Log4j 2 中添加 Throwable

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

我正在尝试记录异常,并希望在日志消息中包含另一个变量的值。是否有 Logger API 可以做到这一点?

logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);

您是否尝试查看 ParameterizedMessage

来自文档

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

例如

logger.error(new ParameterizedMessage("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()), exception);

Log4j 2(和 SLF4J 1.6+)中有一个未记录的功能。 可以将 Throwable 作为最后一个参数传递。然后它会得到特殊待遇。 参见 AbstractLogger#logMessage(String, Level, Marker, String, Object...) and ReusableParameterizedMessage#initThrowable()

ParametrizedMessage 不用费心了。问题中的代码将按预期工作:

logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);