Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting logback.xml path programmatically

Tags:

java

logback

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?

like image 205
shabby Avatar asked Feb 19 '14 16:02

shabby


People also ask

How do I specify the path for Logback xml?

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.

How do I setup a Logback XML file?

In a Logback. xml file, all the configuration options are enclosed within the <configuration> root element. In the root element, you can set the debug=true attribute to inspect Logback's internal status. You can also configure auto scanning of the configuration file by setting the scan=true attribute.

Where can I find Logback xml?

xml or logback. xml can be located directly under any folder declared in the class path. For example, if the class path reads "c:/java/jdk15/lib/rt. jar;c:/mylibs/" then the logback.


2 Answers

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(); 
like image 80
Luca Basso Ricci Avatar answered Sep 24 '22 21:09

Luca Basso Ricci


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.

like image 20
assylias Avatar answered Sep 22 '22 21:09

assylias