Size based RollingFileAppender Configuration – Log4j2

Problem:
How to enable file-size based rolling/archiving of log files in Log4j2.

Solution:
This problem can be solved by using RollingFileAppenders in Log4j2 based logging. Rolling file appenders enable Log4j2 to roll current log file (by renaming it) when certain specific condition or criteria is met for example when current log file size exceeds certain threshold or after specific time duration.

When current log file is rolled, then logging will resume in new log file. You can conveniently specify different paths or filename patterns for current log file as well as rolling file in the configuration of RollingFileAppender.

For example, following RollingFileAppender configuration will automatically roll log file whenever size exceeds 5 KB:

[xml]
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
	<Appenders>
		<RollingFile  name="PaymentApp" fileName="./LogsDir/Payment/PaymentAppLog-${date:yyyyMMdd}.log" filePattern="./LogsDir/Payment/Archv/PaymentAppArchive%d{yyyyMMdd}_%i.txt">
			<PatternLayout>
				<pattern>%d %-5p- %m%n</pattern>
			</PatternLayout>
		        <Policies>
				<OnStartupTriggeringPolicy />
				<SizeBasedTriggeringPolicy size="5KB" />
				<TimeBasedTriggeringPolicy />
		        </Policies>
		</RollingFile>
	</Appenders>
	<Loggers>		
		<Logger additivity="false" level="Info" name="InfoLogger">
				<AppenderRef ref="PaymentApp"/>
		</Logger>
		<Logger additivity="false" level="Error" name="ErrorLogger">
			<AppenderRef ref="PaymentApp"/>
		</Logger>	
	</Loggers>
</Configuration>
[/xml]

In above xml based configuration file:
• We have added a RollingFileAppender (one of the many appenders offered by Log4j2)

• Value of the fileName attribute defines the path and log filename pattern. For example above configuration will generate log file named as “PaymentAppLog-20221109.log” (where current date will always appear in log file name)

• Value of the filePattern attribute defines the path and rolling filename pattern. For example above configuration will generate rolling file named as ”PaymentAppArchive20221109_1.log” (where current date will always appear in rolling file name and _1 refers to rolling file counter which will increment by one automatically for each new rolling file)

• %i in filePattern value means add counter to rolling file name
• %d{yyyyMMdd} in filePattern value means add current date to rolling file name
• ${date:yyyyMMdd} in filename value means add current date to log file name
• %d %-5p- %m%n defines the log file content pattern/layout

Leave a comment