Daily logging with log4j

To generate a daily log with log4j, we have the following options:
  1. Using org.apache.log4j.DailyRollingFileAppender, part of the core Log4j API.
    Configuration in XML:
    <appender name="light" class="org.apache.log4j.DailyRollingFileAppender">
      <param name="File" value="${catalina.base}/logs/light.log" />
      <param name="Append" value="true" />
      <param name="DatePattern" value="'.'yyyy-MM-dd" />
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{HH:mm:ss} %-5p %t %c{2} - %m%n" />
    This will create a file light.log, and at each midnight it will roll, renaming the light.log to something like light.log.2009-09-02
    If you want to configure when the rollover happens, check the possibilities here.
    My only problem here was with the fixed, arbitrary filename (the current date/time is always appended to the end). If you want to change this, you have to look further.

  2. Using org.apache.log4j.rolling.RollingFileAppender from log4j companions you can specify the file-naming conventions as well. Configuration in XML:
    <appender name="light" class="org.apache.log4j.rolling.RollingFileAppender">
      <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" 
               value="${catalina.base}/logs/light-%d{yyyy-MM}.log" />
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
               value="%d{HH:mm:ss} %-5p %t %c{2} - %m%n" />
    By changing FileNamePattern, you can specify the format of the date in the generated log file's name. For more info about the possible configurations see http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/rolling/RollingFileAppender.html. Don't forget to have the Apache Log4J Extras in your classpath!

No comments:

Post a Comment