简体   繁体   English

Log4J 1.2 PropertyConfigurator -> Log4J2

[英]Log4J 1.2 PropertyConfigurator -> Log4J2

Currently, our application uses Log4J 1.2 and configures it using either目前,我们的应用程序使用 Log4J 1.2 并使用以下任一方式对其进行配置

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

or

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

I know that the property file format has changed from 1.2 to 2, but what would be a similar way to configure Log4J 2 using a property file at an arbitrary file or URL?我知道属性文件格式已从 1.2 更改为 2,但是使用任意文件或 URL 中的属性文件配置 Log4J 2 的类似方法是什么?

From Log4J 2's documentation :来自Log4J 2 的文档

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

Make sure to refer to org.apache.logging.log4j.core.LoggerContext (defined in the log4j-core artifact, not the log4j-api one) and not to org.apache.logging.log4j.spi.LoggerContext .确保参考org.apache.logging.log4j.core.LoggerContext (在log4j-core工件中定义,而不是log4j-api )而不是org.apache.logging.log4j.spi.LoggerContext

You can use PropertiesConfigurationBuilder as follows:您可以按如下方式使用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);

It's true that using the core classes looks like a hack but the author himself uses them in his tutotrial: https://logging.apache.org/log4j/log4j-2.3/manual/customconfig.html .确实,使用core类看起来像一个黑客,但作者本人在他的教程中使用了它们: https ://logging.apache.org/log4j/log4j-2.3/manual/customconfig.html。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM