springboot2 log4j2 加载多次 加载两次 配置文件 加载顺序

  • 背景:
    最近笔者对老旧工程进行了springboot的改造,把log4j2.xml改成多环境形式,如:
    +log4j2-dev.xml
    +log4j2-test.xml
    以环境名称作为后缀,在springboot的application.properties配置增加配置:
logging.config=classpath:log4j2-dev.xml
  • 问题:
    由于log4j2.xml中自定义了appender,我发现系统启动的时候log4j2.xml总是加载多次

  • 结果:
    翻阅了一下Log4j的官方文档 https://logging.apache.org/log4j/2.x/manual/configuration.html
    ,发现问题,log4j2-test.xml竟然是log4j2的关键字

Automatic Configuration
Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.

Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.
If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.
If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
  • 知识点:
  1. log4j2配置文件加载顺序:
    log4j2-test.xml > log4j2.xml

2.虽然springboot指定了logging.config=classpath:log4j2-dev.xml,但是log4j2仍然会加载默认的配置文件,然后才加载指定的文件。


淼哥1986 https://www.jianshu.com/u/2263d56f0d37

你可能感兴趣的:(springboot2 log4j2 加载多次 加载两次 配置文件 加载顺序)