4-log4j2之切分日志文件

时间:2021-12-07 06:29:51

一、添加maven依赖

 <dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>

二、日志配置文件log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<properties>
<Property name="console-pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%level] %logger{36} - %msg%n</Property>
<property name="error-file">log4j2learn</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${console-pattern}" />
</Console> <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${error-file}" filePattern="${error-file}-%d{yyyy-MM-dd HH:mm}-%i.log">
<PatternLayout pattern="${console-pattern}" />
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
<!-- 相隔多长时间创建一个新文件,与RollingRandomAccessFile节点的filePattern保持一致,在这个实例中最小时间单位为mm,故每隔1分钟生成一个新日志文件-->
<!-- 超出10kb则另外创建一个新文件保存-->
<SizeBasedTriggeringPolicy size="10 KB" />
</Policies>
</RollingRandomAccessFile>
<Async name="RollingRandomAppender">
<AppenderRef ref="RollingRandomAccessFile" />
</Async>
</Appenders> <Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<appenderRef ref="AsyncAppender" />
</Root>
<Logger name="RandomAccessFileLogger" level="error">
<appenderRef ref="RollingRandomAppender" />
</Logger>
</Loggers> </Configuration>

三、测试代码

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; /**
* @author : zhangyanqing
* @time : 2017/12/9
* @desc : ${DESCRIPTION}
*/
public class RandomAccessLoggerTest {
public static final Logger LOGGER = LogManager.getLogger("RandomAccessFileLogger"); public static void main(String[] args){
for (int i = 0; i< 50000; i++){
LOGGER.trace("trace level");
LOGGER.debug("debug level");
LOGGER.info("info level");
LOGGER.warn("warn level");
LOGGER.error("error level");
LOGGER.fatal("fatal level");
}
}
}