Java – How to configure log4j with a properties file

javalog4jproperties

How do I get log4j to pick up a properties file.

I'm writing a Java desktop app which I want to use log4j. In my main method if have this:

   PropertyConfigurator.configure("log4j.properties");

The log4j.properties file sits in the same directory when I open the Jar.

Yet I get this error:

log4j:ERROR Could not read
configuration file [log4j.properties].
java.io.FileNotFoundException:
log4j.properties (The system cannot
find the file specified)

What am I doing wrong?

Best Answer

I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:

Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);

If the properties file is in the jar, then you could do something like this:

Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);

The above assumes that the log4j.properties is in the root folder of the jar file.