Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j.properties not working in executable jar

I'm using eclipse and I have placed log4j.properties in the project directory and I access it by calling

PropertyConfigurator.configure("log4j.properties");

this works fine in Eclipse, but when I extract the project as an executable Jar and run it on another machine, I get an error saying that it can't find log4j.properties. What is the solution to this?

like image 288
Arya Avatar asked Aug 12 '12 01:08

Arya


People also ask

Where should I place log4j properties file?

The file is named log4j. properties and is located in the $DGRAPH_HOME/dgraph-hdfs-agent/lib directory. The file defines the ROLLINGFILE appenders for the root logger and also sets the log level for the file. The level of the root logger is defined as INFO and attaches the ROLLINGFILE appender to it.

Can we use log4j without properties file?

println() over Log4j, of course for testing purposes, because it doesn't require any configuration, you can just use it, without bothering about XML or properties file configuration, but the most programmer will agree that they would prefer to use Log4j over println statements, even for test programs if it's easy to ...


1 Answers

What's happening

PropertyConfigurator.configure(String) loads and reads a file from the file-system. Your property file is in the project directory, which would be the "current working directory" when you run from eclipse.

Once you've packaged everything up into a jar, and deployed it - only class files and "resources" are placed into the jar. Resources are non-java files that are under your source tree.

After you've copied the jar file to another machine, the properties file is no longer around.

Solutions

Since your properties file isn't a resource, you'll need to move it separately: place a copy of it on the file system (so it can be edited, updated, etc), in your current working directory of your target host/runtime environment.

Consider placing it in some common area of the file system: for example in /tmp/log4j.properties or ~/.myproject/log4j.properties. Your code will have to be adjusted to look for it, accordingly.

Alternative

Copy the properties file into the root of the source tree (/src, be default). It should then be packaged in the jar. Load the data in the jar file as a resource: PropertyConfigurator.configure(getClass().getResourceAsStream()).

In this case, you can't simply edit the file to adjust your logging preferences.

Many times logic will be written to determine if a properties file is on the file system, and if not then load a default from the jar via this mechanism.

like image 67
Richard Sitze Avatar answered Sep 20 '22 11:09

Richard Sitze