Search code examples
javalogback

Setting logback.xml path programmatically


I know I can set the logback.xml path like this:

Specifying the location of the default configuration file as a system property

You may specify the location of the default configuration file with a system property named "logback.configurationFile". The value of this property can be a URL, a resource on the class path or a path to a file external to the application.

java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1

but how can I do it in code?


Solution

  • You could use:

    System.setProperty("logback.configurationFile", "/path/to/config.xml");
    

    But it would have to happen before logback is loaded, i.e. something like:

    class Main {
      static { System.setProperty("logback.configurationFile", "/path/to/config.xml");}
      private final Logger LOG = LoggerFactory.getLogger(Main.class);
    
      public void main (String[] args) { ... }
    }
    

    Note: I have not tested it but it should work.