简体   繁体   English

log4j-slf4j-impl / log4j v2 - 设置自定义 log4j.xml 目标

[英]log4j-slf4j-impl / log4j v2 - setting custom log4j.xml destination

At runtime in my application, I'd like to specify the location of the log4j configuration file dynamically.在我的应用程序运行时,我想动态指定 log4j 配置文件的位置。

This is so that rather than this being a resource bundled in the JAR, it's an actual file on disk that can be edited if there is a problem to increase logging levels.这样一来,它不是捆绑在 JAR 中的资源,而是磁盘上的实际文件,如果在提高日志记录级别时遇到问题,可以对其进行编辑。

When using log4j v1.2, you can use DOMConfigurator.configure(URL) to do this.使用 log4j v1.2 时,可以使用 DOMConfigurator.configure(URL) 来执行此操作。

But now I've upgraded to log4j-slf4j-impl / log4j v2, this method no longer exists.但是现在我已经升级到 log4j-slf4j-impl / log4j v2,这个方法已经不存在了。

I can see how to configure log4j directly, but I want to use the existing slf4j compatible XML file without having to change it.我可以看到如何直接配置 log4j,但我想使用现有的 slf4j 兼容 XML 文件而无需更改它。

Can anyone help?任何人都可以帮忙吗?

Log4j 2.x uses a ConfigurationFactory to parse a configuration file. Log4j 2.x 使用ConfigurationFactory来解析配置文件。 There is a factory for each format and a default factory.每种格式都有一个工厂和一个默认工厂。 The default factory tries to guess the correct format from the file extension of the file: unfortunately both the old Log4j 1.2 and the new Log4j 2.x formats have an .xml extension, so additional configuration is needed.默认工厂尝试从文件的文件扩展名中猜测正确的格式:不幸的是,旧的 Log4j 1.2 和新的 Log4j 2.x 格式都有一个.xml扩展名,所以需要额外的配置67C1C1

In order to parse the Log4j 1.2 XML format you need to add the log4j-1.2.api artifact and replace the default factory:为了解析 Log4j 1.2 XML 格式,您需要添加log4j-1.2.api工件并替换默认工厂:

import org.apache.log4j.xml.XmlConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationFactory;

ConfigurationFactory.setConfigurationFactory(new XmlConfigurationFactory());

After this is set a simple:在这之后设置一个简单的:

Configurator.reconfigure(new URI("URI of your file"));

will apply your configuration to the appropriate LoggerContext .会将您的配置应用于适当的LoggerContext

did you find a solution for this problem?你找到解决这个问题的方法了吗?

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

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