Using RollingFileAppender in log4j for rolling log files

13,315

Solution 1

Lots of examples on the internet, e.g. this creates a daily rolling log file that rolls over to log4jtest.log.2010-08-25 etc

# configure the root logger
log4j.rootLogger=INFO, DAILY

# configure the daily rolling file appender
log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=/tmp/log4j/log4jtest.log
log4j.appender.DAILY.DatePattern='.'yyyy-MM-dd
log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout
log4j.appender.DAILY.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c:%L - %m%n

Solution 2

If you're using XML configuration, you can use the following:

<appender name="MyFileAppender" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="my.log" />
    <param name="Threshold" value="INFO" />
    <param name="DatePattern" value="'.'yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %-10t [%-40.40c] %x - %m%n"/>
    </layout>
</appender>

This rolls the log file over each day.

If you wish to roll the log file over when it reaches a certain size, use RollingFileAppender. From the docs:

RollingFileAppender extends FileAppender to backup the log files when they reach a certain size. The default maximum file size is 10MB.

Share:
13,315
Sameek Mishra
Author by

Sameek Mishra

Updated on June 05, 2022

Comments

  • Sameek Mishra
    Sameek Mishra almost 2 years

    I want to use log4j in my web application. I would like to configure log4j in such a way that when the file reaches a certain size, we start writing a new log files, making it easier to open and read.

    Can you please explain the set up of RollingFileAppender?