如何使用属性文件配置 log4j [英] How to configure log4j with a properties file
问题描述
如何让 log4j 获取属性文件.
How do I get log4j to pick up a properties file.
我正在编写一个想要使用 log4j 的 Java 桌面应用程序.在我的主要方法中,如果有这个:
I'm writing a Java desktop app which I want to use log4j. In my main method if have this:
PropertyConfigurator.configure("log4j.properties");
当我打开 Jar 时,log4j.properties 文件位于同一目录中.
The log4j.properties file sits in the same directory when I open the Jar.
但我收到此错误:
log4j:ERROR 无法读取配置文件 [log4j.properties].java.io.FileNotFoundException:log4j.properties(系统不能找到指定的文件)
log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (The system cannot find the file specified)
我做错了什么?
推荐答案
我相信 configure 方法需要一个绝对路径.无论如何,您也可以尝试先加载一个 Properties 对象:
I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:
Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);
如果属性文件在 jar 中,那么您可以执行以下操作:
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);
以上假设log4j.properties在jar文件的根目录下.
The above assumes that the log4j.properties is in the root folder of the jar file.
这篇关于如何使用属性文件配置 log4j的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!