这是我用来测试 log4j 的 Student 类。
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");
}
}
这是我的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`
当我使用 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)
添加以下代码示例后,即使在命令提示符下运行 jar 文件,也会创建日志文件。
PropertyConfigurator.configure("C:\\eclipeworkspace\\Log4jTest\\log4j.properties");
我如何给出相对路径而不是确切路径?
最佳答案
使用这个:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("log4j.properties");
File file = new File(url.toURI());
关于java - 运行 jar 文件时不创建 Log4j 日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11573510/