Log4j

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:

sample.log.2017-11-15
sample.log.2017-11-14
sample.log.2017-11-13
…
sample.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 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=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Appender2.File=/log/sample.log
log4j.appender.Appender2.DatePattern='.'yyyy-MM-dd
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
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
Minutely'.'yyyy-MM-dd-HH-mmsample.log.2017-11-09-21-54
Hourly'.'yyyy-MM-dd-HHsample.log.2017-11-09-22
Half-daily'.'yyyy-MM-dd-asample.log.2017-11-09-AM
sample.log.2017-11-09-PM
Daily'.'yyyy-MM-ddsample.log.2017-11-09
Weekly'.'yyyy-wwsample.log.2017-45
sample.log.2017-46
Monthly'.'yyyy-MMsample.log.2017-10
sample.log.2017-11

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.:

log4j.appender.Appender2.DatePattern="'_yyyy-MM-dd'.log'"

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.properties

##### LOG4J daily rolling log files configuration #####
log4j.rootLogger=DEBUG, RollingAppender
log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=/log/sample.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.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.

log4j.xml

<?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" />          
       </layout>
    </appender>
    <root>
        <priority value="DEBUG" />
        <appender-ref ref="RollingAppender" />
    </root>
</log4j:configuration>

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.

DynamicRollingLogFile.java

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";
        patternLayoutObj.setConversionPattern(conversionPattern);
 
        // Create Daily Rolling Log File Appender
        DailyRollingFileAppender rollingAppenderObj = new DailyRollingFileAppender();
        rollingAppenderObj.setFile("sample.log");
        rollingAppenderObj.setDatePattern("'.'yyyy-MM-dd");
        rollingAppenderObj.setLayout(patternLayoutObj);
        rollingAppenderObj.activateOptions();
 
        // Configure the Root Logger
        Logger rootLoggerObj = Logger.getRootLogger();
        rootLoggerObj.setLevel(Level.DEBUG);
        rootLoggerObj.addAppender(rollingAppenderObj);
 
        // 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.

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

Yatin

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).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button