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

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

问题描述

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

  logger.error 
\\\
context info one two three:{} {} {} \\\

new Object [] {1,2,3},
新异常(发生错误));

我想生成类似于此的输出:

 上下文信息一二三:1 2 3 
java.lang.Exception:发生错误
stacktrace 0
stacktrace 1
stacktrace ...

slf4j版本1.6.1

解决方案

从SLF4J 1.6.0开始,在存在多个参数的情况下,如果日志记录语句中的最后一个参数是异常,则SLF4J将假定用户想要最后一个参数被视为一个异常而不是一个简单的参数。另请参见相关FAQ条目



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

  logger.error(one two three:{} { } {},a,b,
c,新的异常(发生错误));

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

  logger.error(one two three:{} {} {},new Object [] {a,b,
c ,新的异常(出了问题)});

将产生

 code>一二三:abc 
java.lang.Exception:在Example.main(Example.java:13)
出现错误
java.lang.reflect.Method .invoke(Method.java:597)
at ...

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


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

解决方案

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)

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

or writing (in SLF4J version 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.

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

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