It is possible to configure log4j for splitting up a regular log file into many ones based on a specific schedule, such as daily, weekly, monthly, or even hourly, minutely. This technique is called rolling log files. For example, if the daily schedule is used, log4j would create the following log files:

app.log.2012-10-30
app.log.2012-11-01
app.log.2012-11-02
app.log.2012-11-03
…
app.log
Each log file is rolled out every day, and the file without date in its name is the current log file. Suppose today is 2012-11-04, and at midnight, log4j will back up the app.logfile into app.log.2012-11-04, and the app.log file become logging for the new day, 2012-11-05, and so on. This is very useful when there is a need for tracking log files based on some interval of time. It is also helps to identify problem quickly by inspecting only the relevant log files.

In order to implement daily rolling log files, log4j provides the DailyRollingFileAppender class, which is inheriting from FileAppender class. To use this appender, we need to specify log file name and a date pattern, for example:

log4j.appender.Appender2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Appender2.File=app.log
log4j.appender.Appender2.DatePattern='.'yyyy-MM-dd
The following table shows all the date patterns defined by log4j for daily rolling log files:

 

Schedule

DatePattern

Example of log file’s name

Minutely

'.'yyyy-MM-dd-HH-mm

app.log.2012-11-04-21-54

Hourly

'.'yyyy-MM-dd-HH

app.log.2012-11-04-22

Half-daily

'.'yyyy-MM-dd-a

app.log.2012-11-04-AM

app.log.2012-11-04-PM

Daily

'.'yyyy-MM-dd

app.log.2012-11-04

Weekly

'.'yyyy-ww

app.log.2012-45

app.log.2012-46

Monthly

'.'yyyy-MM

app.log.2012-10

app.log.2012-11

Note that if you want to add literal text to the date pattern, you must escape it in a pair of single quotes, for example:

log4j.appender.Appender2.DatePattern=’_’yyyy-MM-dd’.log’
Let’s see how to implement rolling log files in log4j with different configurations: properties file, xml file, and programmatically.

 

1. Configure log4j daily rolling log files in properties file

Here is an example of a log4j’s properties configuration file which is configured for daily rolling log files:

# LOG4J daily rolling log files configuration
log4j.rootLogger=DEBUG, RollingAppender
log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=app.log
log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd
log4j.appender.RollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n 
 

2. Configure log4j daily rolling log files in XML file



Configure daily rolling log files through log4j’s XML configuration file is as following example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="RollingAppender" class="org.apache.log4j.DailyRollingFileAppender">
       <param name="File" value="app.log" />
       <param name="DatePattern" value="'.'yyyy-MM-dd" />
       <layout class="org.apache.log4j.PatternLayout"> 
          <param name="ConversionPattern" value="[%p] %d %c %M - %m%n"/>           
       </layout> 
    </appender>

    <root>
        <priority value="DEBUG"/> 
        <appender-ref ref="RollingAppender" />
    </root>
    
</log4j:configuration>  
 

3. Configure log4j daily rolling log files in programmatically

Following is an example Java program that configures log4j for daily rolling log files programmatically:

import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.DailyRollingFileAppender;

public class ProgrammaticDailyRollingLogFilesExample {

	public static void main(String[] args) {
		// creates pattern layout
		PatternLayout layout = new PatternLayout();
		String conversionPattern = "[%p] %d %c %M - %m%n";
		layout.setConversionPattern(conversionPattern);

		// creates daily rolling file appender
		DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
		rollingAppender.setFile("app.log");
		rollingAppender.setDatePattern("'.'yyyy-MM-dd");
		rollingAppender.setLayout(layout);
		rollingAppender.activateOptions();

		// configures the root logger
		Logger rootLogger = Logger.getRootLogger();
		rootLogger.setLevel(Level.DEBUG);
		rootLogger.addAppender(rollingAppender);

		// creates a custom logger and log messages
		Logger logger = Logger.getLogger(ProgrammaticDailyRollingLogFilesExample.class);

		logger.debug("this is a debug log message");
		logger.info("this is a information log message");
		logger.warn("this is a warning log message");

	}
}

 

Related Java log4j Tutorials:

 

Other Java Coding Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (log4j_daily.properties)log4j_daily.properties[log4j properties configuration file for daily rolling log files]0.4 kB
Download this file (log4j_daily.xml)log4j_daily.xml[log4j XML configuration file for daily rolling log files]0.6 kB
Download this file (ProgrammaticDailyRollingLogFilesExample.java)ProgrammaticDailyRollingLogFilesExample.java[Example program for configuring daily rolling log files]1 kB

Add comment

   


Comments 

#24Anar2021-11-28 04:03
Hi, I want to that implement this structure for log4j 2. can you share me?
Quote
#23Ravi Ranjan2019-12-26 23:12
Quoting Amit Malyan:
Please do not use DailyRollingFileAppender. Because "DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss." this line is from its offical doc. i have suffered for that when i was trying to log monthly basis. Please friends use some other alternatives.

Can you tell me alternative Idea
Quote
#22Ravi2019-05-30 09:39
I have implemented hourly based DailyRollingFileAppender using log4j.xml file on linux server and found that it is rolling hourly files but can not able to see previous hour logs in my file.
Same implementation is done on windows server and it looks good.
Please advise me like why the behavior of rolling is different from OS specified?
Quote
#21nandha2016-04-01 02:16
I tried with the above sample properties file. And I just have changed the system date for time being. But no such file is created. Ex: app.log.2016-04-01. please let me know. my code is same as in the above example.
Quote
#20nandha2016-04-01 02:14
i tried the above. And changed the system date for time being. But app.log.2016-04-01 is not created even if i run the program again
Quote