Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure log4j with a properties file

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?

like image 463
Dan Avatar asked Feb 18 '10 13:02

Dan


People also ask

Can log4j2 use log4j properties file?

Log4j 2 doesn't support the Log4j v1 ". properties" format anymore (yet, since v2. 4, Log4j supports a Property format, but its syntax is totally different from v1 format). New formats are XML, JSON, and YAML, see the documentation (note: if you used one of these formats in a file called ".


1 Answers

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.

like image 189
kgiannakakis Avatar answered Oct 14 '22 01:10

kgiannakakis