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:
Proper
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.
This is an edit of the answer from @kgiannakakis:
The original code is wrong because it does not correctly close the InputStream after Properties.load(InputStream)
is called. From the Javadocs: The specified stream remains open after this method returns.
================================
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();
InputStream is = new FileInputStream("log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("/log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
You can enable log4j internal logging by defining the 'log4j.debug' variable.
I have this code in my application today
File log4jfile = new File("./conf/log4j.properties");
PropertyConfigurator.configure(log4jfile.getAbsolutePath());
The relative path is from the working directory of the JVM (where the JVM starts).
Since JVM arguments are eventually passed to your java program as system variables, you can use this code at the beginning of your execution point to edit the property and have log4j read the property you just set in system properties
try {
System.setProperty("log4j.configuration", new File(System.getProperty("user.dir")+File.separator+"conf"+File.separator+"log4j.properties").toURI().toURL().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
import org.apache.log4j.PropertyConfigurator;
Import this, then:
Properties props = new Properties();
InputStream is = Main.class.getResourceAsStream("/log4j.properties");
try {
props.load(is);
} catch (Exception e) {
// ignore this exception
log.error("Unable to load log4j properties file.",e);
}
PropertyConfigurator.configure(props);
My java files directory like this:
src/main/java/com/abc/xyz
And log4j directory like this:
src/main/resources