文章目录
- 1.日志模块新增监听器支持外部配置
- 1.common-log4j2-starter项目结构
- 2.修改log4j2.xml为log4j2-spring.xml(这样可以解决读取外部配置但是提前创建目录的问题)
- 3.ApplicationEnvironmentPreparedListener.java 监听器读取配置
- 4.spring.factories 注册监听器
- 5.log4j2-spring.xml 配置从系统属性中读取
- 6.测试
- 1.common-log4j2-starter-demo配置日志根目录和项目模块
- 2.启动测试
- 2.common-log4j2-starter更换banner.txt
- 1.banner.txt
- 2.application.yml
1.日志模块新增监听器支持外部配置
1.common-log4j2-starter项目结构
2.修改log4j2.xml为log4j2-spring.xml(这样可以解决读取外部配置但是提前创建目录的问题)
3.ApplicationEnvironmentPreparedListener.java 监听器读取配置
package com.sunxiansheng.log4j2.listener;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
public class ApplicationEnvironmentPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
String logHome = environment.getProperty("log.home", "./logs");
if ("./logs".equals(logHome)) {
System.err.println("WARNING: log.home 属性未设置,使用默认值: " + logHome);
}
String logModule = environment.getProperty("log.module", "defaultModule");
if ("defaultModule".equals(logModule)) {
System.err.println("WARNING: log.module 属性未设置,使用默认值: " + logModule);
}
System.setProperty("log.home", logHome);
System.setProperty("log.module", logModule);
}
@Override
public int getOrder() {
return LoggingApplicationListener.DEFAULT_ORDER - 1;
}
}
4.spring.factories 注册监听器
org.springframework.context.ApplicationListener=\
com.sunxiansheng.log4j2.listener.ApplicationEnvironmentPreparedListener
5.log4j2-spring.xml 配置从系统属性中读取
<Properties>
<Property name="LOG_HOME">${sys:log.home}</Property>
<Property name="LOG_NAME">sunrays-framework</Property>
<Property name="CONSOLE_LOG_PATTERN">
%style{%d{yyyy-MM-dd HH:mm:ss.SSS}}{green} %style{[%t]}{blue} %highlight{%p}{FATAL=red blink, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, TRACE=magenta} %style{[PFTID:%X{PFTID}]}{magenta} %style{[Module:${sys:log.module}]}{yellow} %style{%logger{36}}{cyan} - %msg%n%throwable
</Property>
<Property name="FILE_LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p [PFTID:%X{PFTID}] [Module:${sys:log.module}] %logger{36} - %msg%n%throwable
</Property>
</Properties>
6.测试
1.common-log4j2-starter-demo配置日志根目录和项目模块
log:
aspect:
enable: true
trace:
enable: true
home: /Users/sunxiansheng/IdeaProjects/sunrays-framework/sunrays-demo/common-log4j2-starter-demo/logs
module: sunrays-demo/common-log4j2-starter-demo
server:
port: 8082
2.启动测试
2.common-log4j2-starter更换banner.txt
1.banner.txt
2.application.yml
spring:
banner:
image:
location: classpath:banner.txt