Log4j2指定配置文件路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guokaikevin/article/details/79190465

上一文中,我们学习了如何利用Log4j2来帮助我们更加优雅的打日志。在项目编译成jar包正式上线的时候,作者遇到了一个问题,就是log4j2.xml将会被打包到jar中,不能再上线后随时更改。

为了能让项目上线后,根据不同的需要改变一些日志的配置信息,如:日志输出路径,日志输出级别等,我们需要对log4j配置文件的加载进行一些变化。对此,可以通过log4jConfigurationSouce来指定配置文件位置,并加载。

ConfigurationSource source;
String relativePath = "log4j2.xml";
String filePath = CONFIG_PATH + System.getProperty("file.separator")
        + relativePath;
File log4jFile = new File(filePath);
try {
    if (log4jFile.exists()) {
        source = new ConfigurationSource(new FileInputStream(log4jFile), log4jFile);
        Configurator.initialize(null, source);
        log = (Logger) LogManager.getLogger("LOGGER_NAME");
        log.debug("this is a debug");
        log.info("this is a info");
        //.....
    } else {
        logInited = false;
        System.out.println("loginit failed");
        System.exit(1);
    }
} catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
}

这样,我们只需要将配置文件放置到CONFIG_PATH路径下,命名为log4j2.xml即可成功加载,如果项目有需要,可以随时更改。

猜你喜欢

转载自blog.csdn.net/guokaikevin/article/details/79190465