Setting logback.xml path programmatically

shabby picture shabby · Feb 19, 2014 · Viewed 53.6k times · Source

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?

Answer

Luca Basso Ricci picture Luca Basso Ricci · Feb 19, 2014
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator configurator = new JoranConfigurator();
InputStream configStream = FileUtils.openInputStream(logbackPropertiesUserFile);
configurator.setContext(loggerContext);
configurator.doConfigure(configStream); // loads logback file
configStream.close();