目前,我们的应用程序使用Log4J 1.2并使用
File file = ...
PropertyConfigurator.configure(file.getAbsolutePath());或
URL url = ...
PropertyConfigurator.configure(url);我知道属性文件的格式已经从1.2改为2,但是使用任意文件或Log4J配置属性文件的类似方法是什么呢?
发布于 2018-01-05 14:12:34
// 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。
发布于 2020-01-13 10:21:44
您可以按以下方式使用PropertiesConfigurationBuilder:
// Custom-loaded properties.
Properties props = ...
// Beware it should be org.apache.logging.log4j.core.LoggerContext class,
// not the one ins spi package!
// Not sure about the meaning of "false".
LoggerContext context = (LoggerContext)LogManager.getContext(false);
Configuration config = new PropertiesConfigurationBuilder()
.setConfigurationSource(ConfigurationSource.NULL_SOURCE)
.setRootProperties(props)
.setLoggerContext(context)
.build();
context.setConfiguration(config);
Configurator.initialize(config);的确,使用core类看起来像一个黑客,但作者自己在他的教程中使用了这些类:https://logging.apache.org/log4j/log4j-2.3/manual/customconfig.html。
https://stackoverflow.com/questions/48115143
复制相似问题