Sunday, 27 February 2022

Logback: Rolling file appender by file size example

Using RollingFileAppender class, we can backup the rolling files by applying RollingPolicy and TriggeringPolicy.

 

Example

<appender name="FILE"
	class="ch.qos.logback.core.rolling.RollingFileAppender">
	<file>${LOG_FILES_HOME}/app.log</file>

	<rollingPolicy
		class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
		<fileNamePattern>${LOG_FILES_HOME}/app.%i.log</fileNamePattern>
		<minIndex>1</minIndex>
		<maxIndex>5</maxIndex>
	</rollingPolicy>

	<triggeringPolicy
		class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
		<maxFileSize>1MB</maxFileSize>
	</triggeringPolicy>

	<encoder>
		<charset>UTF-8</charset>
		<pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
		</pattern>
	</encoder>
</appender>

 

In the above example,

a.   I used FixedWindowRollingPolicy,  FixedWindowRollingPolicy renames files according to a fixed window algorithm. ‘minIndex’ and ‘maxIndex’ specifies lower, upper bounds for window index.

b.   Log file maximum size is set to 1MB, SizeBasedTriggeringPolicy looks at size of the file being currently written to. If it grows bigger than the specified size, the FileAppender using the SizeBasedTriggeringPolicy rolls the file and creates a new one.

 

Find the below working application.

 

Step 1: Create new maven project ‘rolling-file-by-size-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>rolling-file-by-size-demo</artifactId>
	<version>1</version>

	<dependencies>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.2.10</version>
		</dependency>


		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<version>1.2.10</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.36</version>
		</dependency>


	</dependencies>
</project>

Step 3: Create logback.xml file under src/main/resources folder.

 

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
	<property name="LOG_FILES_HOME" value="/Users/Shared/logback" />

	<appender name="consoleAppender"
		class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<charset>UTF-8</charset>
			<Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
			</Pattern>
		</encoder>
	</appender>

	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${LOG_FILES_HOME}/app.log</file>

		<rollingPolicy
			class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
			<fileNamePattern>${LOG_FILES_HOME}/app.%i.log</fileNamePattern>
			<minIndex>1</minIndex>
			<maxIndex>5</maxIndex>
		</rollingPolicy>

		<triggeringPolicy
			class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<maxFileSize>1MB</maxFileSize>
		</triggeringPolicy>

		<encoder>
			<charset>UTF-8</charset>
			<pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
			</pattern>
		</encoder>
	</appender>

	<root level="DEBUG">
		<appender-ref ref="consoleAppender" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

Step 4: Define HelloWorld application.

 

HelloWorld.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
	private static Logger logger = LoggerFactory.getLogger(HelloWorld.class);

	private static void sleep(int noOfSeconds) {
		try {
			TimeUnit.SECONDS.sleep(noOfSeconds);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		while (true) {
			for (int i = 0; i < 10000; i++) {
				logger.trace("Trace message");
				logger.debug("Debug message");
				logger.info("Info message");
				logger.warn("Warning message");
				logger.error("Error message");
			}

			sleep(1);

		}

	}
}

Total project structure looks like below.



Run HelloWorld.java application.

 

Go to the folder /Users/Shared/logback, you will see that log files are roll over.

$pwd
/Users/Shared/logback
$
$ls -lart
total 15872
drwxrwxrwt  14 root     wheel      448 Feb 24 16:09 ..
-rw-r--r--   1 krishna  wheel  1380352 Feb 24 16:51 app.5.log
-rw-r--r--   1 krishna  wheel  1380352 Feb 24 16:51 app.4.log
-rw-r--r--   1 krishna  wheel  1380352 Feb 24 16:51 app.3.log
-rw-r--r--   1 krishna  wheel  1056916 Feb 24 16:51 app.2.log
-rw-r--r--   1 krishna  wheel  1703788 Feb 24 16:51 app.1.log
drwxr-xr-x   8 krishna  wheel      256 Feb 24 16:51 .
-rw-r--r--   1 krishna  wheel   446102 Feb 24 16:51 app.log

 

You can download complete working application from below link.

https://github.com/harikrishna553/java-libs/tree/master/logback/rolling-file-by-size-demo

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment