Log4j2配置替换

文章介绍了如何在公共依赖中设置log4j2.xml配置,并在项目中通过log4j2.component.properties文件引用,实现不同环境的配置切换。同时,文章讲解了如何使用Spring环境配置Log4j2,创建SpringEnvrionmentLookup类以注入Spring上下文信息,并通过SPI机制在spring.factories中注册该类。
摘要由CSDN通过智能技术生成

1、在一个公共依赖下放一个log4j2.xml的默认配置
在这里插入图片描述

2、在需要使用的项目里,引入步骤一中的公共项目,并新建log4j2.component.properties文件,文件内的值为:

log4j.configurationFile=log4j2.xml,log4j2-test2.xml

这个代表使用2个log4j2.xml,并且后边log4j2-test2.xml中配置的属性将会覆盖log4j2.xml中的属性
在这里插入图片描述

当在线上环境需要外部的配置时候可以将log4j2.component.properties中的值改为

log4j.configurationFile=log4j2.xml,log4j2-test2.xml,./config/log4j2-test2.xml

同时在jar包的同级的config中添加log4j2-test2.xml并配置自己的配置

2、使用spring环境配置
2.1、编写配置类


import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.AbstractLookup;
import org.apache.logging.log4j.core.lookup.StrLookup;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;


/**
 * 为log4J2注入spring环境信息
 */
@Plugin(name = "spring", category = StrLookup.CATEGORY)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpringEnvrionmentLookup extends AbstractLookup
        implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static ConfigurableApplicationContext context;


    @Override
    public String lookup(final LogEvent event, final String key) {
        if (context != null) {
            return context.getEnvironment().getProperty(key);
        }
        return null;
    }


    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        context = configurableApplicationContext;
    }
}

2.2、使用spi形式注入
创建META-INF目录并在该目录下创建spring.factories,写入下边的信息

org.springframework.context.ApplicationContextInitializer=\
  配置类全路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值