slf4j:如何记录格式化消息、对象数组、异常 [英] slf4j: how to log formatted message, object array, exception

查看:38
本文介绍了slf4j:如何记录格式化消息、对象数组、异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the correct approach to log both a populated message and a stack trace of the exception?

logger.error(
    "
context info one two three: {} {} {}
",
    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 1.6.1 版

slf4j version 1.6.1

推荐答案

从 SLF4J 1.6.0 开始,在存在多个参数的情况下,如果日志语句中的最后一个参数是异常,那么 SL​​F4J 将假定用户希望将最后一个参数视为异常而不是简单参数.另请参阅相关常见问题解答.

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.7.x 及更高版本中)

So, writing (in SLF4J version 1.7.x and later)

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

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

or writing (in SLF4J version 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 等)以及底层框架的配置方式.但是,如果最后一个参数是异常,则无论底层框架如何,它都会被解释为异常.

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.

这篇关于slf4j:如何记录格式化消息、对象数组、异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆