Search code examples
javaspring-bootlogginglogbackslf4j

Spring Boot | Change slf4j file path programmatically


I need to programmatically set the file path of a Spring Boot application based on a parameter. Currently the log file path is set via the Spring Boot property logging.file. I need to programmatically override this property. The other log properties from the application.properties should remain unchanged.

The logging facade is SLF4J and the logging framework is logback.

What I found so far is that I need to add an ApplicationContextInitializer to my SpringApplication.

The question is, how do I change the log file path in this LoggingInitializer?

public static void main(String[] args) {
    SpringApplication application = new SpringApplication(Main.class);
    application.addInitializers(new LoggingInitializer());
    application.run(args);
}

public class LoggingInitializer implements ApplicationContextInitializer {
  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
      ?....?
  }
}

Solution

  • You can do this, pass --logging.file.path=new-path-to-logs command-line parameter to your app. Just show you a picture of where you need to change;

    String[] nArgs = Arrays.copyOf(args, args.length + 1);
    nArgs[args.length] = "--logging.file.path=./logs2/";
    
    SpringApplication.run(Main.class, nArgs);