gpt4 book ai didi

java - 在 log4j 2 中使用 throwable 和参数

转载 作者:行者123 更新时间:2023-12-03 14:56:52 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

(2 个回答)


20 天前关闭。




我想用一些动态参数记录一个错误(使用 log4j 2),以便更好地理解出了什么问题,我面临的问题是没有像这样的方法:

void error(String message, Throwable t);

带参数支持。

在我的代码中,我希望异常和参数都在消息中填充 {}:
    try {
//...
} catch (Exception e) {
LOGGER.error("Error removing data for account {}", accountId, e);
}

有没有更好的方法来实现它而不是像这样使用它?
LOGGER.error("Error removing token for account " + accountId, e);

最佳答案

实际上,几乎所有接受消息和参数的 log4j 日志记录方法也接受 Throwable。自第一个版本以来,您一直能够做到:

logger.error("Error removing token for account {}", account, ex);
请注意,格式字符串只有一个参数,因此最后的 throwable 被记录为附加到消息的异常。这就是 ParameterizedMessage 类的工作方式。
此外,在 Log4j 2.13.0 中添加了对 LogBuilder 的支持,它允许您执行
logger.atError().withException(ex).log("Error removing token for account {}", account);
这更清楚一点。请注意,将调用以下所有方法,但如果未记录错误级别,则 atError() 之后的所有方法都是无操作的。

关于java - 在 log4j 2 中使用 throwable 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51705617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com