[英]How do you write a full stack trace to the log?
I was catching an exception and trying to write the stack trace to the logs like this:我正在捕获异常并尝试将堆栈跟踪写入日志,如下所示:
log.warn(e.getMessage());
But all it said was但它所说的只是
null
So I changed it to所以我把它改成
log.warn(e.toString());
And now it says only现在它只说
java.lang.NullPointerException
How do I write the full stack trace to the log so I can see where this Exception is being generated in the app?如何将完整的堆栈跟踪写入日志,以便我可以看到在应用程序中生成此异常的位置?
Usually:通常:
log.warn("message", e);
But it depends on your logging framework too.但这也取决于您的日志记录框架。
You can use你可以使用
logger.log(Level.WARN, "logged exception", ex);
or或
logger.warn("logged exception", ex);
Resources :资源:
Using log4j this is done with:使用 log4j,这是通过以下方式完成的:
logger.error("An error occurred", exception);
The first argument is a message to be displayed, the second is the exception (throwable) whose stacktrace is logged.第一个参数是要显示的消息,第二个参数是记录堆栈跟踪的异常(可抛出)。
Another option is commons-logging, where it's the same:另一种选择是 commons-logging,它是相同的:
log.error("Message", exception);
With java.util.logging this can be done via:使用 java.util.logging 这可以通过以下方式完成:
logger.log(Level.SEVERE, "Message", exception);
If you using Java 8 you can do the following:如果您使用 Java 8,您可以执行以下操作:
LOGGER.error("Caught exception while methodX. Please investigate: "
+ exception
+ Arrays.asList(exception.getStackTrace())
.stream()
.map(Objects::toString)
.collect(Collectors.joining("\n"))
);
In your exception method, the underlying String
which contains the message is null
.在您的异常方法中,包含消息的基础String
是null
。
The above answer, now struck out, still holds, except that e
is not null, but the detailMessage
private instance variable on the Throwable
class is null, which is why e.getMessage()
is the String null
, but e.toString()
(which calls underlying null detailMessage.toString
) throws a NullPointerException
.上面的答案,现在被剔除,仍然成立,除了e
不为 null,但Throwable
类上的detailMessage
私有实例变量为 null,这就是为什么e.getMessage()
是 String null
,而e.toString()
(调用底层null detailMessage.toString
)抛出NullPointerException
。
If you are using a Java version previous to 8, you can try this:如果你使用的是 8 之前的 Java 版本,你可以试试这个:
LOGGER.error("Error al recuperar proveedores de la base de datos: " +
e + Arrays.asList(e.getStackTrace()).stream().map(new Function(){
@Override
public Object apply(Object t) {
return t.toString();
}
}).collect(Collectors.joining("\n")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.