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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35096746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:43:49  来源:igfitidea点击:

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

javaexceptionlogginglog4j

提问by derrdji

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 API?

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

采纳答案by DominicEU

Have you tried looking at ParameterizedMessage?

您是否尝试过查看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

参数:

messagePattern - 消息“格式”字符串。这将是一个包含“{}”占位符的字符串,其中应替换参数。

objectArgs - 替换参数。

throwable - 一个 Throwable

回答by Dzmitry

There is an undocumented feature in Log4j 2 (and SLF4J 1.6+). One can pass Throwableas the very last parameter. And it would then get a special treatment. See AbstractLogger#logMessage(String, Level, Marker, String, Object...)and ReusableParameterizedMessage#initThrowable().

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

There is no need to bother with ParametrizedMessage. The code in the question will work just as expected:

没有必要打扰ParametrizedMessage。问题中的代码将按预期工作:

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

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