如何记录格式化消息、对象数组、异常?
记录填充消息和异常堆栈跟踪的正确方法是什么?
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。
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 ...
My SLF4J version is 1.6.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 SLF4J 1.6.0 开始,在存在多个参数的情况下,如果日志记录语句中的最后一个参数是异常,则 SLF4J 将假定用户希望将最后一个参数视为异常而不是简单参数。另请参阅相关常见问题解答条目。
因此,编写(在 SLF4J 版本 1.7.x 及更高版本中)
或编写(在 SLF4J 版本 1.6.x 中)
将产生
确切的输出将取决于底层框架(例如 logback、log4j 等)以及底层框架的方式配置。但是,如果最后一个参数是异常,则无论底层框架如何,它都将被解释为异常。
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.
So, writing (in SLF4J version 1.7.x and later)
or writing (in SLF4J version 1.6.x)
will yield
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.
除了 @Ceki 的答案之外,如果您正在使用 logback 并在项目中设置配置文件(通常是 logback.xml),您还可以定义日志来绘制堆栈跟踪以及使用
模式中的 %ex区别
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
the %ex in pattern is what makes the difference
接受的答案很棒。我只是在这里添加我的案例,该案例现在正在运行,感谢您的回答。这可能对其他人有帮助。
我将
SLF4J
和logback
与 JSON 编码器一起使用。此外,我使用标记
和参数
来丰富我的输出。输出:
当然,在幕后有很多
logstash
配置,但我只是想表明arguments
作为entries
传递显示在配置的eventData
标记中。The accepted answer is great. I'm just adding here my case that is now working thanks for the answer. This may help someone else.
I'm using
SLF4J
andlogback
with a JSON encoder. Furthermore, I usemarker
andarguments
to enrich my output.The output:
Of course there is a lot of configuration of
logstash
behind the scenes, but I just wanted to show that thearguments
passed asentries
are shown in the configuredeventData
tag.