动态修改log4j.properties配置文件,无需重启就可以生效

1.log4j.properties自带有一个PropertyConfigurator的类,通过方法configureAndWatch实现

代码实现

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.PropertyConfigurator;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/**
 * @author: zhaobin
 * @date: 2021/8/25 17:29
 * @description:
 */
@Slf4j
public class Test {
    static {
        PropertyConfigurator.configureAndWatch("./log4j.properties", 6000);
    }

    public static void printLog() throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("D:\\project\\mytest\\target\\classes\\log4j.properties"));
        Set<String> keys = properties.stringPropertyNames();
        for (String key : keys) {
            System.out.println(key + "="+ properties.getProperty(key));
        }
    }

    public static void main(String[] args) throws IOException {
        while (!Thread.interrupted()) {
            Test.printLog();
            System.out.println("-----------------------------");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        }
    }
}

通过手动修改log4j.properties的参数,每过6秒,就会重新读取配置文件,并且进行加载.

2.第一次使用了apollo,发现哪怕提升了apollo的初始化顺序也无法实现动态读取,并且报错,找不到配置

3.使用了io流,在程序加载完毕之后,写个方法,读取apollo的配置,然后写入到log4j.properties中,因为用的是k8s,镜像和容器的方式部署服务,也不顺利,路径是一大问题

4.最终使用了这种自带的方式进行,效果明显

posted @ 2021-09-23 14:41  CodingChangeTheWorld  阅读(1094)  评论(0编辑  收藏  举报