log4j - Configure RollingFileAppender for backup log files as DailyRollingFileAppender

5.9k views Asked by At

Whether we can configure RollingFileAppender get function as DailyRollingFileAppender. That mean I want to backup (rotates) logs files daily basis with the usage of 'max file size' and 'max number of dates witch log files can keep' (RollingFileAppender related maxBackupIndex and maxFileSize properties). Issue is, with DailyRollingFileAppender we can not configure maxBackupIndex and maxFileSize properties. Thanks.

1

There are 1 answers

2
Paul Vargas On BEST ANSWER

Unfortunately, this is not possible using the standard API of log4j or even with the extras 1.

However, you can use the class uk.org.simonsite.log4j.appender.TimeAndSizeRollingAppender 2 developed by Simon Park:

If you use XML-based configuration, here is an example:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration>
<log4j:configuration>

    <appender name="ROLL" class="uk.org.simonsite.log4j.appender.TimeAndSizeRollingAppender">
        <param name="File" value="app.log"/>
        <param name="DatePattern" value=".HHmmss"/>
        <param name="MaxFileSize" value="10KB"/>
        <param name="MaxRollFileCount" value="5"/>
        <layout class="org.apache.log4j.SimpleLayout" />
    </appender>

    <root>
        <appender-ref ref="ROLL"/>
    </root>

</log4j:configuration> 

For this particular example, the generated files are similar to:

app.log
app.log.155144.1
app.log.155144.2
app.log.155144.3
app.log.155144.4
app.log.155144.5
app.log.155400.1
app.log.155400.2
app.log.155400.3
app.log.155400.4
app.log.155400.5
app.log.161646.1
app.log.161646.2
app.log.161646.3
app.log.161646.4
app.log.161646.5
app.log.161706.1
app.log.161706.2
app.log.161706.3
app.log.161706.4

Notes

  1. Apache Extras™ for Apache log4j™ in http://logging.apache.org/log4j/extras/
  2. You need to download the respective jar from http://www.simonsite.org.uk/download.htm or if you are using Maven, add to your pom.xml:
    <repositories>
        <repository>
            <id>opencast-public</id>
            <url>http://repository.opencastproject.org/nexus/content/repositories/public/</url>
        </repository>
        ...
    </repositories>
    ...
    <dependencies>
        <dependency>
            <groupId>uk.org.simonsite</groupId>
            <artifactId>log4j-rolling-appender</artifactId>
            <version>20131024-2017</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        ...
    </dependencies>