[英]What is the difference between LOGGER.error(exception.getMessage()) and LOGGER.error(exception.getMessage(), exception)
LogEvent
可以同時包含消息和異常。 如果您使用第一種形式:
LOGGER.error(exception.getMessage());
只會記錄錯誤消息,您的日志中會有類似的 output(取決於布局):
[ERROR] - Exception message.
如果您使用第二種形式:
LOGGER.error(exception.getMessage(), exception);
您將同時收到消息和異常。 這通常會在日志中輸出堆棧跟蹤:
[ERROR] - Exception message.
java.lang.RuntimeException: Exception message.
at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]
由於您始終可以配置 Log4j 2.x 以抑制來自 output 的堆棧跟蹤(請參閱PatternLayout
文檔中的alwaysWriteExceptions
),因此第二種形式總是更好,因為它提供了更多信息。
備注:由於堆棧跟蹤總是打印錯誤消息,我建議使用第三種形式:
LOGGER.error("An unexpected condition occurred while performing foo: {}",
exception.getMessage(), exception);
這樣您就可以在發生異常時解釋上下文:
[ERROR] - An unexpected condition occurred while performing foo: Exception message.
java.lang.RuntimeException: Exception message.
at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.