这是我用来测试 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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的log4j.properties文件
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`
Run Code Online (Sandbox Code Playgroud)
当我使用 Eclipse 运行该程序时,会创建MyLogExample.log文件。但是,在我创建 jar 文件并使用命令提示符运行它之后,未创建日志文件。
在控制台中我可以看到这个错误。
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (The system cannot find the file specified)
Run Code Online (Sandbox Code Playgroud)
添加以下代码示例后,即使 jar 文件在命令提示符下运行,也会创建日志文件。
PropertyConfigurator.configure("C:\\eclipeworkspace\\Log4jTest\\log4j.properties");
Run Code Online (Sandbox Code Playgroud)
我如何给出相对路径而不是确切路径?
log4j.properties应该在你的类路径中。从命令行运行时将其添加到类路径中。
更好的选择是使用指定属性文件
-Dlog4j.configuration=relative path/log4j.properties
从命令行。在这种情况下,您可以从代码中删除该行PropertyConfigurator.configure("log4j.properties");- 您不需要在代码中执行任何操作来指定属性文件。