Java slf4j:如何记录格式化消息、对象数组、异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6371638/
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
slf4j: how to log formatted message, object array, exception
提问by rowe
What is the correct approach to log both a populated message and a stack trace of the exception?
记录填充消息和异常堆栈跟踪的正确方法是什么?
logger.error(
"\ncontext info one two three: {} {} {}\n",
new Object[] {"1", "2", "3"},
new Exception("something went wrong"));
I'd like to produce an output similar to this:
我想产生与此类似的输出:
context info one two three: 1 2 3
java.lang.Exception: something went wrong
stacktrace 0
stacktrace 1
stacktrace ...
slf4j version 1.6.1
slf4j 版本 1.6.1
回答by Ceki
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
从 SLF4J 1.6.0 开始,在存在多个参数的情况下,如果日志语句中的最后一个参数是异常,那么 SLF4J 将假定用户希望将最后一个参数视为异常而不是简单参数。另请参阅相关的常见问题解答条目。
So, writing (in SLF4J version 1.7.x and later)
所以,写作(在 SLF4J 1.7.x 及更高版本中)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
或写作(在 SLF4J 版本 1.6.x 中)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
会屈服
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 ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
确切的输出将取决于底层框架(例如 logback、log4j 等)以及底层框架的配置方式。但是,如果最后一个参数是异常,则无论底层框架如何,它都会被解释为异常。
回答by Yaniv
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
除了@Ceki 的回答,如果您在项目中使用 logback 并设置一个配置文件(通常是 logback.xml),您还可以定义日志以绘制堆栈跟踪以及使用
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
模式中的 %ex 是与众不同的