FallbackErrorHandler
:
1. Create a backup appender:The backup appender will be used if the primary appender fails. My backup is a
ConsoleAppender
:
<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>2. Add a FallbackErrorHandler to your primary appender:
My primary appender is a
DailyRollingFileAppender
. Add a FallbackErrorHandler
to it and tell it to use the "console" (backup) appender, using the appender-ref
tag. The root-ref
tag refers to the logger that is currently using that appender. If you have a different logger use the logger-ref
tag to refer to it instead.
<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>3. Trying it out:
To test this works, make your log file read-only, or change the path of the file to one which doesn't exist. When you run your application, you will see log4j print an error to stderr, and start logging to console, instead of file. If you turn log4j debug on you will see the message: "FB: INITIATING FALLBACK PROCEDURE." before console logging begins. The complete log4j.xml configuration:
Here is my complete config file. (I tried setting up a log4j.properties file, but ran into problems and wasn't able to.)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <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> <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>
Thanks you so much. This is very helpful for my project
ReplyDeleteThank you very much. I will try this.
ReplyDeleteThanks, this is the most useful thing I found online about using ErrorHandlers with log4j.
ReplyDelete