使用log4j,如果FileAppender在寫入指定日誌文件時遇到問題,我想恢復爲ConsoleAppender。這意味着捕獲FileNotFoundException或IOException並切換到ConsoleAppender。如果FileAppender失敗,恢復到ConsoleAppender
一直這樣做過的事情,否則我將不得不創建一個新的appender - 東西線沿線的:
private WriterAppender appender;
public FileOrConsoleAppender(Layout layout, String filename, boolean append) {
try {
appender = new FileAppender(layout, filename, append, bufferedIO, bufferSize);
}
catch (IOException e) {
appender = new ConsoleAppender(layout);
}
}
更新 - 我怎麼沒IT:
感謝@jsight,指向我FallBackErrorHandler。
這裏是我的log4j xml配置其恢復到一個是ConsoleAppender,如果FileAppender失敗:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
<!-- A Console appender -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %30.30c - %m%n"/>
</layout>
</appender>
<!-- A File appender, with fallback to Console-->
<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">
<errorHandler class="org.apache.log4j.varia.FallbackErrorHandler">
<root-ref/>
<appender-ref ref="console"/>
</errorHandler>
<param name="File" value="C:/temp/test.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %30.30c - %m%n"/>
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="file" />
</root>
</log4j:configuration>