[英]Log4j Log is not created when jar file run
這是我用來測試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());
log4j.properties
應該在你的類路徑中。 從命令行運行時將其添加到類路徑。
更好的選擇是使用指定屬性文件
-Dlog4j.configuration=relative path/log4j.properties
從命令行。 在這種情況下,您可以刪除PropertyConfigurator.configure("log4j.properties");
從您的代碼 - 您不需要在代碼中執行任何操作來指定屬性文件。
添加此插件,如果使用maven使你的jar可以運行所有的依賴性
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<mainClass>cnnc.bcyr.nvnvn.nch.MainclassName</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.