因为我的是springboot项目,所以pom如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉默认配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
</dependencies>
log4j2.xml如下:
<?xml version="1.0" encoding="utf-8" ?> <Configuration status="INFO"> <Appenders> <RollingFile name="runtimeFile" fileName="./logs/active.log" filePattern="./logs/%d{yyyy-MM-dd.HH}.log" append="true"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS Z}\t%level\t%class\t%line\t%thread\t%msg%n" /> <Policies> <TimeBasedTriggeringPolicy /> </Policies> <!-- 此行以下为自动清理日志的配置 --> <DefaultRolloverStrategy> <Delete basePath="./logs"> <!-- glob 项为需要自动清理日志的pattern --> <IfFileName glob="*.log"/> <!-- 1d 表示自动清理掉1天以前的日志文件 --> <IfLastModified age="24H"/> </Delete> </DefaultRolloverStrategy> <!-- 此行以上为自动清理日志的配置 --> </RollingFile> </Appenders> <Loggers> <Root level="INFO" additivity="false"> <!--<AppenderRef ref="console" />--> <AppenderRef ref="runtimeFile" /> </Root> </Loggers> </Configuration>
注意:关于log4j2的定时删除如果filePattern的粒度为HH,那么在<IfLastModified age="24H" />中如果age=1d则不生效