Log4J 1.2属性配置器->Log4J2

2022-04-12 00:00:00 java log4j2

目前,我们的应用程序使用Log4J 1.2并使用

File file = ...
PropertyConfigurator.configure(file.getAbsolutePath());

URL url = ...
PropertyConfigurator.configure(url);

我知道属性文件格式已从1.2更改为2,但使用任意文件或URL上的属性文件配置Log4J 2的类似方式是什么?


解决方案

发自Log4J 2's documentation:

// 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());

确保引用org.apache.logging.log4j.core.LoggerContext(在log4j-core项目中定义,而不是log4j-api)和NOT到org.apache.logging.log4j.spi.LoggerContext

相关文章