解决重载logf4j2配置文件问题
1 问题:重载logf4j2配置文件
2 解决方案
2.1 官方文档:How do I reconfigure log4j2 in code with a specific configuration file?
https://logging.apache.org/log4j/2.x/faq.html#config_from_code
// import org.apache.logging.log4j.core.LoggerContext; 可以配置本地文件 LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false); File file = new File("path/to/a/different/log4j2.xml"); // this will force a reconfiguration context.setConfigLocation(file.toURI());
2.2 使用ConfigurationFactory 创建
//ConfigurationFactory的实现类 :XmlConfigurationFactory,YamlConfigurationFactory, InputStream = null; in = new FileInputStream(new File("path/to/a/different/log4j2.xml")); ConfigurationSource source = new ConfigurationSource(inputStream); Configuration configuration = new XmlConfigurationFactory().getConfiguration(context, source); context.setConfiguration(configuration);
2.3 使用Nacos解决
@NacosConfigListener(dataId = "log4j2.yml") public void onMessage(String config) throws UnsupportedEncodingException { System.out.println(config); LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false); InputStream inputStream = new ByteArrayInputStream(config.getBytes("UTF-8")); try { ConfigurationSource source = new ConfigurationSource(inputStream); Configuration configuration = new YamlConfigurationFactory().getConfiguration(context, source); context.setConfiguration(configuration); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }