SpingBoot分段输出日志并自动删除
-
引入log4j2依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
需要排除掉SpringBoot自带日志框架
<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>
-
在application.propreties中配置
#日志 logging.config=classpath:log4j2.xml
-
在Resouces目录下新建log4j2.xml
<?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"><Properties><Property name="LOG_DIR">./logs</Property><Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property></Properties><Appenders><!-- 控制台输出 --><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="${LOG_PATTERN}"/></Console><!-- 每天滚动一次的日志文件 --><RollingFile name="RollingFile"fileName="${LOG_DIR}/app.log"filePattern="${LOG_DIR}/app-%d{yyyy-MM-dd}.log"><PatternLayout pattern="${LOG_PATTERN}"/><Policies><!-- 每天滚动一次(interval="1" 默认按天) --><TimeBasedTriggeringPolicy interval="1" modulate="true"/></Policies><DefaultRolloverStrategy><!-- 删除超过 14 天的日志 --><Delete basePath="${LOG_DIR}" maxDepth="1"><IfFileName glob="app-*.log"/><!-- 保留最近 14 天的日志 --><IfLastModified age="14d"/></Delete></DefaultRolloverStrategy></RollingFile></Appenders><Loggers><Root level="info"><AppenderRef ref="Console"/><AppenderRef ref="RollingFile"/></Root></Loggers></Configuration>