记录填充消息和异常堆栈跟踪的正确方法是什么?
logger.error(
"\ncontext info one two three: {} {} {}\n",
new Object[] {"1", "2", "3"},
new Exception("something went wrong"));
Run Code Online (Sandbox Code Playgroud)
我想生成类似于此的输出:
context info one two three: 1 2 3
java.lang.Exception: something went wrong
stacktrace 0
stacktrace 1
stacktrace ...
Run Code Online (Sandbox Code Playgroud)
slf4j版本1.6.1
从我在网上找到的许多示例,文档以及此处的Stack Overflow中,在slf4j中连接字符串的正确方法是使用内置的字符串格式。
例如 :
LOGGER.error("ExceptionHandler throws {}" , appException);
Run Code Online (Sandbox Code Playgroud)
我也尝试了不格式化,并且产生了相同的结果:
LOGGER.error("ExceptionHandler throws " , appException);
Run Code Online (Sandbox Code Playgroud)
由于某种原因,这对我不起作用,我也不知道自己缺少什么。如果传递对象,是否使用其他格式?
上面的示例正在打印以下日志消息:
2018-07-18 02:38:19 ERROR c.a.c.c.p.ExceptionProcessor:67 - ExceptionHandler throws {}
Run Code Online (Sandbox Code Playgroud)
而不是使用常规串联时收到的预期消息:
LOGGER.error("ExceptionHandler throws " + appException);
Run Code Online (Sandbox Code Playgroud)
或者当我手动调用.toString()时
LOGGER.error("ExceptionHandler throws {}" , appException.toString());
Run Code Online (Sandbox Code Playgroud)
根据Sonar的说法,这最后一个选项不正确,因为:
因为printf样式的格式字符串是在运行时解释的,而不是由编译器验证的,所以它们可能包含导致创建错误字符串的错误。在调用java.util.Formatter,java.lang.String,java.io.PrintStream,MessageFormat和java.io的format(...)方法时,此规则静态验证printf样式格式字符串与其参数的相关性。 .PrintWriter类和java.io.PrintStream或java.io.PrintWriter类的printf(...)方法。
AppException类如下:
import java.io.Serializable;
import javax.ws.rs.core.Response.Status;
public class AppException extends Exception implements Serializable {
private static final long serialVersionUID = 1L;
private Error error;
private Status status;
public AppException(Error error, Status status) {
this.error = error;
this.status …Run Code Online (Sandbox Code Playgroud)