记录填充消息和异常堆栈跟踪的正确方法是什么?
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 等)以及底层框架的配置方式。但是,如果最后一个参数是异常,则无论底层框架如何,它都会被解释为异常。
我是一名优秀的程序员,十分优秀!