views:

444

answers:

2

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?

+1  A: 

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.

kgiannakakis
An absolute path in the jar or the filesystem?
Dan
An absolute path in the filesystem. Use getResource if the file is in the jar.
kgiannakakis
Have you got an example of how to do that?
Dan
See my edited answer
kgiannakakis
A: 

You can enable log4j internal logging by defining the 'log4j.debug' variable.

Jeach