How can I change the default location of log4j2.xml in Java Spring Boot?

后端 未结 6 1317
醉梦人生
醉梦人生 2020-12-14 09:37

Log4j2 is working nicely with Spring Boot through the log4j2.xml configuration file in the root classpath, exactly as the documentation states.

When try

6条回答
  •  星月不相逢
    2020-12-14 09:46

    The answer of micpalmia is absolutely correct.

    I needed to put the configuration outside the classpath I didn't want to pass the config file as a parameter. So i put a very simple logging configuration in the classpath resources and had the spring boot application reconfigure logging upon start, like so:

    @SpringBootApplication
    public class Application implements CommandLineRunner {
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void run(String... param) throws UnsupportedEncodingException {
            Configurator.initialize(null, "config/log4j2.xml");
            // ...
        }
    }
    

    This approach has a significant disadvantage: The whole application boot process will not be logged as externally configured. But once the custom code is run the logger works as intended. While you may not, I find this to be a compromise I can live with.

提交回复
热议问题