I want to put all my config files in a /config
subfolder of my application directory. Log4j is expecting the log4j.properties file in the root folder of my application. Is there a way to tell log4j where to look for the properties file?
59
votes
7 Answers
77
votes
Yes, define log4j.configuration
property
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Note, that property value must be a URL.
For more read section 'Default Initialization Procedure' in Log4j manual.
34
votes
You can use PropertyConfigurator
to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
4
votes
2
votes
Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);
0
votes
0
votes
This is my class : Path is fine and properties is loaded.
package com.fiserv.dl.idp.logging;
import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggingCapsule {
private static Logger logger = Logger.getLogger(LoggingCapsule.class);
public static void info(String message) {
try {
String configDir = System.getProperty("config.path");
if (configDir == null) {
throw new MissingResourceException("System property: config.path not set", "", "");
}
Properties properties = new Properties();
properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
PropertyConfigurator.configure(properties);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(message);
}
public static void error(String message){
System.out.println(message);
}
}