I’m using log4j for my logging purposes. To configure everything, I’ve made a log4j.xml that is outside of the jar-file. It works great, but gives problems when the jar-file isn’t executed from the same directory where the log4j.xml is.
Example: jar-file is in /opt/myapp/test.jar
user@host:/opt/myapp$ java -jar test.jar
works great, but when I try this:
user@host:~$ java -jar /opt/myapp/test.jar
I get an error that log4j.xml cannot be found. That’s because it is looking for it in my current working directory.
I also have a properties file that I use in my application. This file is in the config/ directory where the jar-file is, so /opt/myapp/config in this example. The same issue like the one above occurs when trying to load the config file.
How can I let Java load a file from the directory where the jar-file is (no matter from where the jar is executed)?
Probably something very easy, but I can’t figure it out 🙁
Specify using log4j system property, add this before that “-jar” part of the command:
-Dlog4j.configuration=/opt/myapp/log4j.xml
Add the directory to the classpath, add this before that “-jar” part of the command:
-cp /opt/myapp/
You can specify the log4j.xml file manually in code and then reference it relative your jar file.
Fetch file from specific directory where jar file is placed
String path = … ;
PropertyConfigurator.configure(path);