Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a logback configuration as a classpath resource rather than a file

Tags:

logback

I have the following situation. I need to be able to run two programs launched by different batch files where each batch file invokes a java class with main() from the same jar. I would like each program to have its own log. However, the second program is an installer for the first, and therefore, I don't want to/can't easily specify -Dlogback.configurationFile=/path/to/config file as that location may not yet exist.

Logback documentation seems to provide a solution but I need an example of how to make it work:

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

If you wish, you can 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

Can anyone point me to an example where logback.configurationFile is defined as a resource on the classpath as opposed to the file system?

like image 476
Steve Cohen Avatar asked Oct 25 '12 13:10

Steve Cohen


2 Answers

OK I went ahead and tried it out.

If the logback config file is local to the jar (in the same jar you're running in), this works:

System.setProperty("logback.configurationFile", "org/package/path/your.logback.xml");

works. If it's in the classpath 'anywhere'. Which is really weird since normally with a call to getResource you have to specify it with a preceding slash like:

YourClass.class.getResource("/org/package/path/your.logback.xml") so not sure why.

Other more exotic resource paths like specifying the exact jar also seem to not work. Weird.

like image 73
rogerdpack Avatar answered Sep 19 '22 18:09

rogerdpack


You can simply put a my-logback.xml in the root of one of your classpath entries and specify -Dlogback.configurationFile=my-logback.xml. Internally it will probably use ClassLoader#getResource(String name) to get the file - check the JavaDoc of this method for more information.

like image 23
Christoph Leiter Avatar answered Sep 19 '22 18:09

Christoph Leiter