When I put together a program that outputs logs using log4j into a jar file, log4j.xml, which is the log4j configuration file, did not load properly.
The structure of the project looks like this.
├ src
└ foo
└ foo.java <=Main program
└ resources
└ log4j.xml <=log4j config file
In the constructor of the main program, I read the configuration file as follows.
foo.java
import org.apache.log4j.xml.DOMConfigurator;
public class foo {
public foo () {
DOMConfigurator.configure("log4j.xml");
}
}
By specifying the file name log4j.xml
, when I test it on Eclipse, it loads well, but when I run this project as a jar file, it fails with an error that the file cannot be found.
When I made the project into a jar file and called it from another program, it looked for the file log4j.xml
in the startup directory of that program, so it seems that it could not be found successfully.
Therefore, instead of specifying only the file name, specify the absolute path to the file.
By rewriting the constructor as follows, you can specify the absolute path, and even if you put the project together in a jar file, the configuration file will be read well.
foo.java
public foo () {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
DOMConfigurator.configure(loader.getResource("log4j.xml"));
}
Recommended Posts