事实证明,有时log4j2是不安全的。记录消息可能会引发异常,从而可能破坏功能。我认为这不是理想的日志行为-日志记录应该失败而不会崩溃。这是一个基本示例:
InstrumentedAppender = new InstrumentedAppender (..);
appender.start();
...
appender.stop();
final Logger logger = LogManager.getLogger("LOG4J_TEST");
try {
logger.error("TEST_ERROR");
} catch (Exception e){
System.out.println("-------------- Exception is thrown");
e.printStackTrace()
}
在我的输出中,我得到了:
org.apache.logging.log4j.core.appender.AppenderLoggingException: Attempted to append to non-started appender org.apache.logging.log4j.core.Appender
at org.apache.logging.log4j.core.config.AppenderControl.handleError(AppenderControl.java:142)
at org.apache.logging.log4j.core.config.AppenderControl.ensureAppenderStarted(AppenderControl.java:135)
at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:127)
at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:448)
at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:433)
at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:417)
...........
有什么办法可以避免应用程序中的这种日志行为?
答案 0 :(得分:1)
这可以通过追加程序上的ignoreExceptions标志设置:
默认值为true,导致在追加事件时遇到的异常会在内部记录,然后被忽略。设置为false时,异常将传播到调用方。在将此Appender包装在FailoverAppender中时,必须将其设置为false。