简体   繁体   English

log4j 1.x 中错误方法的区别

[英]Differences between error methods in log4j 1.x

In the logging part of the project I working for, I try to optimize the error messages that are shown in log management.在我工作的项目的日志记录部分,我尝试优化日志管理中显示的错误消息。 Logging error messages is coded like this:记录错误消息的编码如下:

String errorMessage =" Problem with server "+"\n"+t.getMessage();
_logger.fatal(errorMessage);

Where t is a Throwable object and _logger is a Logger object, which is related to the log4j framework.其中t为Throwable对象,_logger为Logger对象,与log4j框架相关。

What I wonder is, what changes if I use _logger.fatal(errorMessage, t);我想知道的是,如果我使用_logger.fatal(errorMessage, t);会发生什么变化_logger.fatal(errorMessage, t); instead of _logger.fatal(errorMessage);而不是_logger.fatal(errorMessage); ? ? If there is a major difference between them, Which one will be better to use?如果它们之间存在重大差异,那么使用哪个更好?

Edit: I've just realised I copied "fatal" example instead of "error".编辑:我刚刚意识到我复制了“致命”示例而不是“错误”。 However my question is same for fatal, too.然而,我的问题对于致命的也是一样的。

Practically all Java logging framework (alas, we have plenty of those...) support putting a Throwable as the last parameter.实际上所有 Java 日志框架(唉,我们有很多这样的框架)都支持将Throwable作为最后一个参数。

This will result in a stack trace being logged, which can be extremely useful in diagnosing and fixing the problem.这将导致记录堆栈跟踪,这对于诊断和修复问题非常有用。

I'd only ever not give the exception to the logger if the cause of the exception is really well established and printing the exception is just unnecessary noise.如果异常的原因确实确定并且打印异常只是不必要的噪音,我只会永远不会向记录器提供异常。 For example here:例如这里:

try {
   int port = Integer.parseInt(input);
   // do something with the port
} catch (NumberFormatException e) {
   logger.error("'{}' is not a valid port number: {}", input, e.toString);
}

Another case is when the exception is being re-thrown (and something else will eventually log it with more detail).另一种情况是当异常被重新抛出时(其他东西最终会用更多的细节记录它)。

But not with a "Problem with server" (and at FATAL level no less).但不是“服务器问题”(并且在致命级别不少)。 That looks like you want to get as much info as you can get.看起来您想获得尽可能多的信息。

Also note that in those cases, e.toString() is usually better than e.getMessage() because it also includes the name of the exception in addition to its message (which may be empty).另请注意,在这些情况下, e.toString()通常比e.getMessage()更好,因为除了消息(可能为空)之外,它还包括异常的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM