欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > log4j2.xml 使用 application.yml 配置的属性

log4j2.xml 使用 application.yml 配置的属性

2025/4/21 14:37:08 来源:https://blog.csdn.net/asd54090/article/details/140380527  浏览:    关键词:log4j2.xml 使用 application.yml 配置的属性

参考:https://www.jianshu.com/p/1f2427c87139

log4j2.xml 是不归 spring 管理的,所以也就没法读取到 application.yml 里面的配置了。 解决方式: 通过 spring 的 监听器(Listener)功能,将我们读取到的 application.yml 的日志路径设置到系统属性,然后在日志文件里面读取对应的系统属性就行了。

LoggingListener.java

通过 spring 的 监听器(Listener)功能,将我们读取到的 application.yml 的日志路径设置到系统属性,或者使用MDC

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;/*** 读取yml配置传递到log4jXml中** @author Clay*/
@Component
public class LoggingListener implements ApplicationListener<ApplicationEvent>, Ordered {/*** 提供给日志文件读取配置的key,使用时需要在前面加上 sys:*/private final static String LOG_PATH = "log.path";/*** spring 内部设置的日志文件的配置key*/private final static String SPRING_LOG_PATH_PROP = "spring.log-file-path";@Overridepublic void onApplicationEvent(ApplicationEvent applicationEvent) {if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent) {ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) applicationEvent).getEnvironment();String filePath = environment.getProperty(SPRING_LOG_PATH_PROP);if (StringUtils.isNotEmpty(filePath)) {System.err.println("=================" + filePath);System.setProperty(LOG_PATH, filePath);}}}@Overridepublic int getOrder() {// 当前监听器的启动顺序需要在日志配置监听器的前面,所以此处减 1return LoggingApplicationListener.DEFAULT_ORDER - 1;}}

application.yml

spring: log-file-path: "F:/logs/"

log4j2.xml

<Property name="log-path">${sys:log.path}</Property>

Application.java

这里没有贴出注解,关键于.addListeners(new LoggingListener())

内置Tomcat

public class Application {public static void main(String[] args) {SpringApplication application = new SpringApplication(Application.class);// 添加 日志监听器,使 log4j2-spring.xml 可以间接读取到配置文件的属性application.addListeners(new LoggingListener());application.run(args);}}

外置Tomcat

public class TomcatApplication extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {// 添加 日志监听器,使 log4j2-spring.xml 可以间接读取到配置文件的属性builder.application().addListeners(new LoggingListener());return builder.sources(Application.class);}}

转至:https://blog.csdn.net/xiaokanfuchen86/article/details/126695797

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词