log4j.properties not working in executable jar

11,825

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.

Share:
11,825
Arya
Author by

Arya

Updated on July 02, 2022

Comments

  • Arya
    Arya almost 2 years

    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?