Log4j

Log4j 2 RollingFileAppender example

In this example we shall talk about the RollingFileAppender, one of the most basic appenders of Log4j. Log4j a thread-safe and flexible logging library for Java, licensed under the Apache Software Foundation.

The log4j architecture has three basic components, the logger, the appender and the layout. The logger is used to log the messages, the appender publishes the messages to different outputs and layout is used to format the log messages. All these components are configured in the log4j.xml file, which is placed in the application classpath.

A basic appender that is frequently used in log4j is the RollingFileAppender. It is an OutputStreamAppender that writes log messages to files, following a configured triggering policy about when a rollover should occur, and also following a configured rollover strategy about how to rollover the file.
Below, we will configure the RollingFileAppender to log files to a file, making use of its basic configuration parameters and using Log4j 2.

Tip
You may skip project creation and jump directly to the beginning of the example below.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using the JDK 7_u_21.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project
Figure 1. New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

New Maven Project 2
Figure 2. New Maven Project 2

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "log4jexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.log4jexample " and the project name as "log4jexample". Hit “Finish” to exit the wizard and to create your project.

log4j example
Figure 3. log4j example

The Maven project structure is shown below:

log4j example structure
Figure 4. log4j example structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add log4j 2 dependencies

Add the log4j 2 dependencies in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor, as shown below:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>log4jexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
<dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.0.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.0.2</version>
  </dependency>
</dependencies>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Create the log4j2.xml file

The log4j2.xml file is placed under the resources folder of the project. This is where all logging components are configured. The rootLogger is set here, binded to a logging level and to the appender. The rootlogger is the logger configured in the log4j2.xml file, unless there is a custom logger implementation to be used in the application.

The logging levels are (from smaller to greater) : ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF. When a logging level is set, only messages belonging to this level or greater levels are printed.

Here, we use the RollingFileAppender to log messages to a file. The basic RollingFileAppender parameters to configure are described below:

  • append : when this field is set to true, the appender will append new logs to the file, when false ti will clear previous logs and write from the beginning.
  • immediateFlush : When set to true, every log record is immediately flushed to disk, if false, batch flushing is performed, thus improving the logger performance.
  • bufferedIO : If set to true, a buffer is used to write data and when the buffer is full the data is flushed.
  • bufferSize : This is the buffer size that will lead to data flush when reached.
  • filter : Here, we can define one or more filters to check if the records should be logged or not.
  • fileName : The name of the file that the appender writes to. If the file does not exist, it is created.
  • filePattern : This is where the pattern of the file is configured.
  • layout : This is the layout used to format the log event.
  • name : Here the appender name is set.
  • policy : The TriggeringPolicy to perform a rollover. The TriggeringPolicy may be composite, that combines multiple triggering policies and returns true if any of the configured policies return true. It may be on startup, that causes a rollover if the log file is older than the current JVM’s start time or it may be size based and time based, that cause a rollover according to size and time setting accordingly. The time based triggering policy uses two extra parameters, interval and modulate, to set how often the rollover will occur and wether it will occur on the interval boundary.
  • strategy : The RolloverStrategy that determines the name and location of the archived file. The default strategy may use the date/time pattern and the filePattern attributes specified on the RollingFileAppender. So, the date/time is replaced by current time in rollover, and if the filePattern has integer counter, the counter is incremented in rollover.
  • ignoreExceptions : When set to true, internal exceptions will be logged and then ignored. When set to false, exceptions will be propagated to the caller, instead, or can also be propagated to a FailoverAppender.

Below, we have focused on configuring the parameters that are related to rollover, so we have set the strategy and policy of the appender, as also the layout of log events and the fileName of files. We are using a SizeBasedTriggeringPolicy, with size set to 1 KB, so we expect the file to rollover when it reaches this size. We are also using a DefaultRolloverStrategy, with max number of files equal to 4, so we expect that the files in our logs folder will reach the max number of 4, and then the oldest ones will be removed as new ones will be created.

The layout used for the log events is:

  • %d{dd/MMM/yyyy HH:mm:ss,SSS} : the date pattern
  • %c{1} : print the class name
  • %m : print the message
  • %n to leave an empty line

The filePattern is set to ${log-path}/myexample-%d{yyyy-MM-dd}-%i.log, where the ${log-path} is set as a property in the file and sets the initial path of the logs folder, and %i is the counter that will be automatically incremented in rollover.

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Properties>
<Property name="log-path">C:/logs/</Property>
</Properties>
<Appenders>
<RollingFile name="RollingFile" fileName="${log-path}/myexample.log"
filePattern="${log-path}/myexample-%d{yyyy-MM-dd}-%i.log" >
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="1 KB" />
</Policies>
<DefaultRolloverStrategy max="4"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="root" level="debug" additivity="false">
<appender-ref ref="RollingFile" level="debug"/>
</Logger>
<Root level="debug" additivity="false">
<AppenderRef ref="RollingFile"/>
</Root>
</Loggers>
</Configuration>

4. Create an Example class

Example.java class gets the rootLogger to log messages to the console. The logger is stated as a static field, initialized by the getLogger(String name) API method of org.apache.logging.log4j.LogManager. Example.java class has a main method, where the user is asked to type a number. The logger logs messages of different levels, using info(Object message), warn(Object message), debug(Object message), error( Object message) and fatal(Object message) API methods.

Example.java:

package com.javacodegeeks.snippets.enterprise.log4jexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class Example {

	static Logger log = LogManager.getLogger(Example.class.getName());

	public static void main(String[] args) throws IOException {
		System.out.println("===> Please enter a number:\n===>");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int number = Integer.valueOf(br.readLine());
		log.info("Info : number is " + number);
		log.warn("Warning : number is " + number);
		log.debug("Debug : number is " + number);
		log.error("Error : number is " + number);
		log.fatal("Fatal : number is " + number);
		
		if(number > 100) {
			log.info("Info : You chose a number > 100 ");
			log.warn("Warning : You chose a number > 100 ");
			log.debug("Debug : You chose a number > 100 ");
			log.error("Error : You chose a number > 100 ");
			log.fatal("Fatal : You chose a number > 100 ");
			
		} else {
			log.info("Info : You chose a number < 100 ");
			log.warn("Warning : You chose a number < 100 ");
			log.debug("Debug : You chose a number < 100 ");
			log.error("Error : You chose a number < 100 ");
			log.fatal("Fatal : You chose a number < 100 ");			
		}
		String numberStr = String.valueOf(number);
		for(int i=0; i<=10; i ++) {
			if(numberStr.contains(String.valueOf(i))) {
				log.info("Info : Your number has the digit " + i);
				log.warn("Warning : Your number has the digit " + i);
				log.debug("Debug : Your number has the digit " + i);
				log.error("Error : Your number has the digit " + i);
				log.fatal("Fatal : Your number has the digit " + i);
			}
		}
	}
}

5. Run the application

Run the application more than once. Since the logging level is set to DEBUG, we expect that all logs will be produced and writen in the file. Since the file size is set to just 1 KB, rollover will occur immediately. You can change the logging level, and the policy and strategy params in the configuration file to practice more.

6. Download the Eclipse Project

This was an example of Log4j RollingFileAppender.

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

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

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

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
daniel
daniel
5 years ago

thanks, this was helpful for configuration

Sha
Sha
4 years ago

if i run application from different main class how to create file name as per main class

sneha dabriwal
sneha dabriwal
3 years ago

hello , getting rolling file exception in case of multi instance in docker , how to handle.

Back to top button