This is my Student class that used to test log4j.
public class Student{
private static final Logger logger = Logger.getLogger(Student.class.getName());
public Student() {
PropertyConfigurator.configure("log4j.properties");
}
public static void main(String args[]){
logger.log(Level.INFO, "My log4j Test");
}
}
This is my log4j.properties file
log4j.rootLogger=INFO,Appender1,Appender2
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender2=org.apache.log4j.RollingFileAppender
log4j.appender.Appender2.File=C:/Log4j/MyLogExample.log
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout`
log4j.appender.Appender1.Target=System.out`
log4j.appender.Appender1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n`
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout`
log4j.appender.Appender2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n`
log4j.appender.Appender2.MaxFileSize=50KB`
log4j.appender.Appender2.MaxBackupIndex=10`
When I run this program using Eclipse MyLogExample.log file gets created. But after I have created a jar file and run it using the command prompt, the log file is not created.
in console i can see this error.
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (The system cannot find the file specified)
After I add the following code example, the log file is created even when the jar file run with command prompt.
PropertyConfigurator.configure("C:\\eclipeworkspace\\Log4jTest\\log4j.properties");
How I can give relative path instead of exact path?
log4j.propertiesshould be in your classpath. Add it to the classpath when running from command line.A better alternative is to specify the property file using
-Dlog4j.configuration=relative path/log4j.propertiesfrom the command line.
In this case you can remove the line
PropertyConfigurator.configure("log4j.properties");from your code – you don’t need to do anything in the code to specify the property file.