Log4j Rolling Daily File Example

Logging is a critical feature of any application. In this tutorial, I will show you how to implement some useful Log4j RollingFileAppender Patterns for writing the logging mechanism in Java development.

1. Introduction

Printing messages to the console is an integral part of the development testing and the debugging of a Java program. If developers are working on a Server side application, where they cannot see what’s going on inside the server, then their only visibility tool is a log file.

Without logs, developers cannot do any debugging or see what’s going on inside the application. Java has pretty handy System.out.println() methods to print something on the console, which can also be routed to a log file but it is not sufficient for a real-world Java application.

If developers are running a Java program in Linux or in Unix based systems, Log4j or SLF4j or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System.out.println() statements.

1.1 What is Log4j?

Log4j is a simple, flexible, and fast Java-based logging framework. It is thread-safe and supports internationalization. We mainly have 3 components to work with Log4j:

  • Logger: It is used to log the messages
  • Appender: It is used to publish the logging information to the destination like file, database, console etc
  • Layout: It is used to format logging information in different styles

1.1.1 Log4j2 Appender Interface

Appender is an interface which is primarily responsible for printing the logging messages to the different destinations such as console, files, sockets, database etc. In Log4j2 we have different types of Appender implementation classes:

Fig. 1: Log4j Appenders
Fig. 1: Log4j Appenders

2. Log4j Daily Rolling Log File Example

It is possible to configure the 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. Let’s say for e.g., If the daily rolling file schedule is used, then Log4j would create the following log files:


Each log file is rolled out every day and the file without date in its name is the current log file. Suppose today is 2017-11-16 and at midnight, Log4j will back up the current sample.log file into the sample.log. 2017-11-16. The original sample.log will now become the current logging file for the new day i.e. 2017-11-17 and so on. This approach is very useful when there is a need for tracking the log files based on some interval of time. It also helps to quickly identify the problem by inspecting only the relevant log files.

In order to implement the Daily Rolling Log files, Log4j framework provides the DailyRollingFileAppender class which is inherited from the FileAppender class. To use this Appender, developers would need to specify the log file name and a date pattern. I tried to make a small modification in the original version of the DailyRollingFileAppender to add the maxBackupIndex property. This property will help developers to clean up the old log files which may be required for the future usage.

Let’s see the simple code snippet that follows the DailyRollingFileAppender implementation.

log4j.appender.Appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

The following table shows all the date patterns defined by the Log4j framework for the Daily Rolling Log files:

ScheduleDatePatternExample of Log File’s Name

Note that if developers want to add the literal text to the date pattern, they must escape it in a pair of single quotes. For e.g.:


Now, let’s see how to implement the rolling log files in Log4j framework through different configurations i.e. via Properties file, XML file, and Programmatically.

2.1 Configure 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.layout.ConversionPattern=[%p] %d %c %M - %m%n

2.2 Configure Daily Rolling Log Files in XML file

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


<?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="/log/sample.log" />
       <param name="DatePattern" value="'.'yyyy-MM-dd" />
       <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="[%p] %d %c %M - %m%n" />          
        <priority value="DEBUG" />
        <appender-ref ref="RollingAppender" />

2.3 Configure Daily Rolling Log Files Programmatically

Following is an example of Java program that programmatically configures the Log4j for daily rolling log files.


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 DynamicRollingLogFile {
    public static void main(String[] args) {
        // Creates Pattern Layout
        PatternLayout patternLayoutObj = new PatternLayout();
        String conversionPattern = "[%p] %d %c %M - %m%n";
        // Create Daily Rolling Log File Appender
        DailyRollingFileAppender rollingAppenderObj = new DailyRollingFileAppender();
        // Configure the Root Logger
        Logger rootLoggerObj = Logger.getRootLogger();
        // Create a Customer Logger & Logs Messages
        Logger loggerObj = Logger.getLogger(DynamicRollingLogFile.class);
        loggerObj.debug("This is a debug log message");
        loggerObj.info("This is an information log message");
        loggerObj.warn("This is a warning log message");

That’s all for this post. Happy Learning!!

3. Conclusion

That’s all for getting the developers started with the Log4j Daily Rolling files example. We will look into more features in the next posts. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

4. Download the Eclipse Project

This was an example of Log4j Rolling File Example.

You can download the full source code of this example here: Log4j DailyRollingFileAppender


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button