Java 您如何将完整的堆栈跟踪写入日志?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3717249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you write a full stack trace to the log?
提问by Linc
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?
如何将完整的堆栈跟踪写入日志,以便我可以看到在应用程序中生成此异常的位置?
采纳答案by Peter ?tibrany
Usually:
通常:
log.warn("message", e);
But it depends on your logging framework too.
但这也取决于您的日志记录框架。
回答by Colin Hebert
You can use
您可以使用
logger.log(Level.WARN, "logged exception", ex);
or
或者
logger.warn("logged exception", ex);
Resources :
资源 :
回答by Noel M
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 nulldetailMessage.toString
) throws a NullPointerException
.
上面的答案,现在被剔除,仍然成立,除了它e
不是 null,但是类上的detailMessage
私有实例变量Throwable
是 null,这就是e.getMessage()
String 的原因null
,但是e.toString()
(调用基础nulldetailMessage.toString
)抛出一个NullPointerException
.
回答by Joseph Rajeev Motha
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);
回答by nishant
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"))
);
回答by RafaJR
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")));