以编程方式加载Log4j2配置文件

时间:2014-01-13 04:21:43

标签: java logging log4j2

我想从我的应用程序中以编程方式加载Log4j2 XML配置文件。

试过这个:

ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
Configurator.initialize(null, source);

和此:

ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
ConfigurationFactory factory = (ConfigurationFactory) XMLConfigurationFactory.getInstance().getConfiguration(source);
ConfigurationFactory.setConfigurationFactory(factory);

但是没有任何作用。

7 个答案:

答案 0 :(得分:35)

对于最新版本的log4j,以下是加载外部log4j2.xml的工作原理:

String log4jConfigFile = System.getProperty("user.dir") + File.separator + "log4j2.xml";
ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4jConfigFile));
Configurator.initialize(null, source);

答案 1 :(得分:16)

如果您有一个主要入口点,此代码段可能会为您省去一些麻烦。必须在创建任何记录器之前触发set属性调用。此方法适用于类路径上的文件。

public class TestProcess {
    static {
        System.setProperty("log4j.configurationFile", "log4j-alternate.xml");
    }

    private static final Logger log = LoggerFactory.getLogger(TestProcess.class);

}

答案 2 :(得分:13)

自己找到答案。有人可能觉得它很有用。

ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
source.setFile(new File(logConfigurationFile));
source.setInputStream(new FileInputStream(logConfigurationFile));
Configurator.initialize(null, source);

答案 3 :(得分:4)

以下为我工作的Log4j2使用SLF4J包装器:

解决方案1:

public class MyClass {

    static {
        try {
            InputStream inputStream = new FileInputStream("C:/path/to/log4j2.xml");
            ConfigurationSource source = new ConfigurationSource(inputStream);
            Configurator.initialize(null, source);
        } catch (Exception ex) {
            // Handle here
        }
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class); // LogManager if not using SLF4J

    public void doSomething() {
        LOGGER.info(...)
    }

}

解决方案2:

static {
    File log4j2File = new File("C:/path/to/log4j2.xml");
    System.setProperty("log4j2.configurationFile", log4j2File.toURI().toString());
}

需要toURI()跟随File URI Scheme format,否则会抛出MalformedURLException

来源:

答案 4 :(得分:1)

答案 5 :(得分:0)

final URL log4j = Resources.getResource("log4j2-test.xml");
LoggerContext.getContext(false)
  .start(new XmlConfiguration(new ConfigurationSource(
    Resources.asByteSource(log4j).openStream(),
    log4j)));

答案 6 :(得分:0)

如果使用.properties文件进行配置:

String propertiesFile = "./test/Configuration/log4j2.properties";  
ConfigurationSource source = new ConfigurationSource(new FileInputStream(propertiesFile), new File(propertiesFile));
Configurator.initialize(null, source);