Tuesday, November 24, 2009

Extra features for Log4j DailyRollingFileAppender

Log4j has some nice features and supports many appenders, but so far we never had a file appender with all features as it should be. Recently we wanted to write our own appender but before doing so we found Ryan Kimber already had the same idea and did a good job rewriting the original DailyRollingFileAppender: the CustodianDailyRollingFileAppender. On his blog he provides some info on how he updated the appender. We made some very small changes to make it completely working for us and to make sure the log file directory is created if it didn't exist.



  • make sure the directory structure to the specified log file exists

  • create a new log file for each day

  • compress log files older than today

  • remove log files older than a specified number of days


CustodianDailyRollingFileAppender.java source


Example of log4j configuration:



log4j.rootLogger=INFO, FILE
log4j.appender.FILE=com.myt.common.logging.CustodianDailyRollingFileAppender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{MMM dd yyyy HH:mm:ss,SSS} [%t] %-5p %l - %m%n
log4j.appender.FILE.File=/var/log/myt.log
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.MaxNumberOfDays=30
log4j.appender.FILE.CompressBackups=true

No comments:

Post a Comment