我有一个使用 log4j 的 Eclipse Java 项目。我无法将 log4j 配置文件设置为按文件路径访问。我必须导出项目并在 jar 中运行。
这是我尝试的方式:
public class Wita {
static Logger logger;
public static void main(String[] args) {
System.setProperty("log4j.configuration", new File("").getCanonicalPath()+File.separatorChar+"resources"+File.separatorChar+"log4j.xml" );
// System.out.println( System.getProperty("log4j.configuration") );
logger = Logger.getLogger(Wita.class.getName());
}
}
系统输出打印 C:\Users\roncsak\eclipse_workspace\WITA\resources\log4j.xml 这很好。 WITA 是项目的基础文件夹。但使用 -Dlog4j.debug 参数运行项目时,也会返回以下结果:
log4j: Trying to find [C:\Users\roncsak\eclipse_workspace\WITA\resources\log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@18e3e60. log4j: Trying to find [C:\Users\roncsak\eclipse_workspace\WITA\resources\log4j.xml] using sun.misc.Launcher$AppClassLoader@18e3e60 class loader. log4j: Trying to find [C:\Users\roncsak\eclipse_workspace\WITA\resources\log4j.xml] using ClassLoader.getSystemResource(). log4j: Could not find resource: [C:\Users\roncsak\eclipse_workspace\WITA\resources\log4j.xml].
我想随着时间的推移更改 log4j.xml,而不构建另一个 jar 文件。我该怎么做?
最佳答案
来自 http://logging.apache.org/log4j/1.2/manual.html 的“默认初始化程序” :
- Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
- Attempt to convert the resource variable to a URL.
- If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string "log4j.properties" constitutes a malformed URL. See Loader.getResource(java.lang.String) for the list of searched locations.
因此,您需要将 file:
添加到 log4j.configuration
属性值中,以便将其视为 URL。
参见 https://stackoverflow.com/a/7927278/603516 .
更好的代码:
System.setProperty("log4j.configuration", new File("resources", "log4j.xml").toURL());
关于java - 如何设置 log4j 属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12579468/