Log4j2介绍和特性实例(六)--配置文件不在默认路径下的加载

    xiaoxiao2022-07-06  218

      Log4j2介绍和特性实例(六)--配置文件不在默认路径下的加载

    转载: https://blog.csdn.net/chenhaotong/article/details/50528090

    1. Log4j2配置文件的默认路径是src文件夹,如果打包程序的话,配置文件会被写死到Jar包中,用户不能随时修改配置文件。

    因此,如果把配置文件放到项目的根路径下,则程序打包后,配置文件可以与Jar包放到同一路径下,便于用户修改编辑。

    这样的话,需要在Java主程序中进行如下设置,1)引入ConfigurationSource

    import org.apache.logging.log4j.core.config.ConfigurationSource;

     

    2)在函数中加载项目根目录下的配置文件:

    /** * 加载项目根目录下的log4j2.xml文件 * 应用程序打包后,xml可以与Jar包放到同一个目录下,方便用户修改日志等级 * */ public String setLogConfigFilePath(){ ConfigurationSource source; //method2 System.getProperty String config = System.getProperty("user.dir"); String fullPath = config + "\\log4j2.xml"; System.out.println("Log4j2 fullPath = " + fullPath); File file = new File(fullPath); //this ConfigurationSource() could load xml dynamicly, info->debug->info test OK!!! try { source = new ConfigurationSource(new FileInputStream(file), file); Configurator.initialize(null, source); logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fullPath; }

    注意:如果项目中使用了Maven等项目管理工具,在变更xml路径的时候,最好在项目目录下搜索是否有其他路径下保存的多余的log4j2.xml,有的话删除。

    下面将介绍如何在代码中指定日志文件的名字。谢谢。

    最新回复(0)