Spring Boot programmatic logging configuration

前端 未结 1 1353
北恋
北恋 2020-12-16 16:43

How can I configure logging programmatically in a spring boot application?

Using an xml or properties file is not flexible enough for my needs.

相关标签:
1条回答
  • 2020-12-16 17:17

    I'm not sure you want or need to disable the default XML configuration of the logging system, but you do want to execute your customization calls after that was done. Fortunately that's pretty easy as it's done as early as possible in the initializer chain for a SpringApplication. The easiest place to put your code is probably a SpringApplicationInitializer (it has to implement ApplicationContextInitializer as well so it can be added to the SpringApplication). E.g.

    SpringApplication application = new SpringApplication(MySources.class);
    application.addInitializers(new LoggingInitializer());
    application.run(args);
    

    You won't be able to do dependency injection into the initializer if you do it that way, but it will ensure that it gets called as early as possible in the lifecycle. If your initializer implements EnvironmentAware then you will also be passed an instance of Environment before the call to SpringApplicationInitializer.initialize() - using that you can resolve the environment dependent pieces in your sample, e.g.

    String loggingLevelRoot = environment.getProperty("logging.level.root");
    

    Once you have it working, to avoid having to do the same thing for all apps you can make it declarative by adding a META-INF/spring.factories containing your initializer class:

    org.springframework.context.ApplicationContextInitializer=\
    my.pkg.for.LoggingInitializer
    

    If you really need dependency injection and @Value resolution I think you are going to have to accept that the ApplicationContext will have fully refreshed before you get a chance to configure anything. If that's an acceptable compromise I recommend just adding a LoggingInitializer to your context and have it implement CommandLineRunner.

    0 讨论(0)
提交回复
热议问题