Java 记录异常,使用 getMessage 或 toString :log.warn(ex.getMessage()) 或 log.warn(ex) 使用开源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28272473/
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
Java Logging exceptions, use getMessage or toString : log.warn(ex.getMessage()) or log.warn(ex) working with open source
提问by tgkprog
My question is: it better to log with getMessage or with toString or both? taking in to account errors thrown by open source. Saw the questions in the comments but did not get an answer to this. Maybe I missed something ? Do not mind the small performance hit of logging one of them, but do not want to log both unless there is a good reason.
我的问题是:最好使用 getMessage 或 toString 或两者同时登录?考虑到开源引发的错误。看到评论中的问题,但没有得到答案。也许我错过了什么?不要介意记录其中一个对性能的小影响,但除非有充分的理由,否则不要同时记录两者。
Meaning log(ex) or log(ex.getMessage), Not talking about stack trace.
意思是 log(ex) 或 log(ex.getMessage),不是在谈论堆栈跟踪。
Logging exceptions : which is better: log.warn(ex.getMessage(), ex) or log.warn(ex, ex);
记录异常:哪个更好:log.warn(ex.getMessage(), ex) 或 log.warn(ex, ex);
I noticed sometimes getMessage returns empty or null, so in general practice is there any reason not to use :
我注意到有时 getMessage 返回空或空,所以在一般实践中是否有任何理由不使用:
log.warn(ex, ex);
As it seems to print the class name and the message (if set) ? I guess one reason could be if a sub class has over ridden to string not to print the message, but in reality do any of the hibernate, apache or spring libs do that?
因为它似乎打印了类名和消息(如果设置了)?我想一个原因可能是如果一个子类过度使用字符串而不是打印消息,但实际上任何休眠、apache 或 spring 库都这样做吗?
回答by Thilo
How about
怎么样
log.warn("some descriptive message, maybe with context {}",
someId, ex);
The exception details will already be printed as part of the stacktrace, so you don't need to include them in the message usually.
异常详细信息已经作为堆栈跟踪的一部分打印出来,因此您通常不需要将它们包含在消息中。
In case you want to suppress the stacktrace and only print the exception message, usually, ex.toString()
works better than ex.getMessage()
, because it also includes the exception class name, which the message does not. In fact, often the message is empty (for example with NullPointerExceptions).
如果您想抑制堆栈跟踪并只打印异常消息,通常ex.toString()
比 更有效ex.getMessage()
,因为它还包含异常类名称,而消息不包含该名称。事实上,通常消息是空的(例如 NullPointerExceptions)。