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.最終使用了這種自帶的方式進行,效果明顯