您的位置:首页 > 移动开发

Log4j 2 - RollingFileAppender example 日志分割

2017-10-11 15:21 525 查看
echnologies used:   Java SE 1.8 | Log4j 2.8.2 | Maven 3.3.9 | Jackson API 2.8.7 | Eclipse Neon.3RollingFileAppender is a file appender which rolls over the log files once it has reached a certain size limit or date/time pattern no longer applies.In this post, I will show you how to use the 
RollingFileAppender
 tobackup and compress the old log files based on - Date and TimeSize of log fileCron expression

Jar dependencies

Edit 
pom.xml
 file and add log4j2 and JacksonAPI dependencies in it.
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>

Rolling based on Date and Time

You can use the TimeBasedTriggeringPolicy torollover the log file based on the date and time pattern used in 
<FilePattern/>
elementas follows.
<RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/time-based-logs/%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="2" modulate="true" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
Here are sample date/time patterns for rolling of files base on date/time.
DATE/TIME PatternDescriptionIntervale Attribute Example
%d{yyyy-MM-dd-hh-mm}.log.zipRoll the log files every minutesIf interval=2, rollovers will occur every 2nd minutes.E.g. - 2017-07-26-09-57.log.zip, 2017-07-26-09-59.log.zip, 2017-07-26-10-01.log.zip, 2017-07-26-10-03.log.zip etc..
%d{yyyy-MM-dd-hh}.log.zipRoll the log files hourlyIf interval=4, rollovers will occur every 4 hours.E.g. - 2017-07-26-09.log.zip, 2017-07-26-10.log.zip, 2017-07-26-11.log.zip etc..
%d{yyyy-MM-dd}.log.zipRoll the log files dailyIf interval=1, rollovers will occur every day.E.g. - 2017-07-26.log.zip, 2017-07-27.log.zip etc..
The following is the complete example of 
log4j2.xml
 filefor rolling files every 2nd minutes.log4j2.xml
<?xml version="1.0" encoding="UTF-8"?><Configuration><Appenders><!-- Console Appender --><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" /></Console><!-- Rolling File Appender --><RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/time-based-logs/%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="2" modulate="true" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile></Appenders><Loggers><Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false"><AppenderRef ref="RollingFile" /><AppenderRef ref="Console" /></Logger><Root level="trace"><AppenderRef ref="Console" /></Root></Loggers></Configuration>
The 
<DefaultRolloverStrategy>
 element definea rollover strategy that will keep up to 5 files before removing them.A simple Java program to test the above log4j 2 configuration.MainApp.java
package com.boraji.tutorial.log4j2;

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

public class MainApp {

private static final Logger logger = LogManager.getLogger(MainApp.class);

public static void main(String[] args) {

for (int i = 0; i < 10000; i++) {
logger.info("Rolling file appender example...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
 

Rolling based on size of file

You can use the SizeBasedTriggeringPolicy torollover the log file based on the size of file as follows.
<RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/size-based-logs/%d{yyyy-MM-dd-hh}-%i.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 KB"/>
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
You can specify the size of file in bytes, with the suffix KB, MB or GB.Here is the complete 
log4j2.xml
 file forrolling files based on the specified size in 
<SizeBasedTriggeringPolicy/>
 element.log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>

<!-- Console Appender -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
</Console>

<!-- Rolling File Appender -->
<RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/size-based-logs/%d{yyyy-MM-dd-hh}-%i.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 KB" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>

</Appenders>
<Loggers>
<Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false">
<AppenderRef ref="RollingFile" />
<AppenderRef ref="Console" />
</Logger>
<Root level="trace">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
The following is a simple java program to test the above log4j2.xml configuration.
package com.boraji.tutorial.log4j2;

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

public class MainApp {

private static final Logger logger = LogManager.getLogger(MainApp.class);

public static void main(String[] args) {

for (int i = 0; i < 50000; i++) {
logger.info("Rolling file appender example...");
}

}
}

Rollingbased on cron expression

You can use the CronTriggeringPolicy torollover the log file based on the specified cron expression as follows.
<RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/cron-based-logs/%d{yyyy-MM-dd-hh-mm}-%i.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<CronTriggeringPolicy schedule="0 0/2 * 1/1 * ? *" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
The following is the complete 
log4j2.xml
 file,which trigger rollover after every 2nd minutes as specified in 
schedule
 attribute of
<CronTriggeringPolicy/>
 elementby cron expression.log4j2.xml
<?xml version="1.0" encoding="UTF-8"?><Configuration><Appenders><!-- Console Appender --><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" /></Console><!-- Rolling File Appender --><RollingFile name="RollingFile">
<FileName>C:/log/mylog.log</FileName>
<FilePattern>C:/log/cron-based-logs/%d{yyyy-MM-dd-hh-mm}-%i.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<CronTriggeringPolicy schedule="0 0/2 * 1/1 * ? *" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile></Appenders><Loggers><Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false"><AppenderRef ref="RollingFile" /><AppenderRef ref="Console" /></Logger><Root level="trace"><AppenderRef ref="Console" /></Root></Loggers></Configuration>
The following is a simple java program to test the above log4j2.xml configuration.
package com.boraji.tutorial.log4j2;

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

public class MainApp {

private static final Logger logger = LogManager.getLogger(MainApp.class);

public static void main(String[] args) {

for (int i = 0; i < 1000; i++) {
logger.info("Rolling file appender example...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
https://www.boraji.com/log4j-2-rollingfileappender-example

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  log4j2