gpt4 book ai didi

java - 如何记录格式化消息、对象数组、异常?

转载 作者:bug小助手 更新时间:2023-10-28 10:39:52 25 4
gpt4 key购买 nike

记录填充消息和异常堆栈跟踪的正确方法是什么?

logger.error(
"\ncontext info one two three: {} {} {}\n",
new Object[] {"1", "2", "3"},
new Exception("something went wrong"));

我想产生类似这样的输出:

context info one two three: 1 2 3
java.lang.Exception: something went wrong
stacktrace 0
stacktrace 1
stacktrace ...

我的 SLF4J 版本是 1.6.1。

最佳答案

从 SLF4J 1.6.0 开始,在存在多个参数的情况下,如果日志语句中的最后一个参数是异常,则 SLF4J 将假定用户希望将最后一个参数视为异常而不是简单的范围。另见relevant FAQ entry .

所以,写作(在 SLF4J 版本 1.7.x 及更高版本中)

 logger.error("one two three: {} {} {}", "a", "b", 
"c", new Exception("something went wrong"));

或写作(在 SLF4J 版本 1.6.x 中)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
"c", new Exception("something went wrong")});

将产生

one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...

确切的输出将取决于底层框架(例如 logback、log4j 等)以及底层框架的配置方式。但是,如果最后一个参数是异常,则无论底层框架如何,它都会被解释为异常。

关于java - 如何记录格式化消息、对象数组、异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6371638/

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