我有一个使用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());
}
}
Run Code Online (Sandbox Code Playgroud)
系统输出打印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文件.我怎样才能做到这一点?
Vad*_*zim 22
从http://logging.apache.org/log4j/1.2/manual.html上的 "默认初始化过程" :
- 将资源字符串变量设置为log4j.configuration系统属性的值.指定默认初始化文件的首选方法是通过log4j.configuration系统属性.如果未定义系统属性log4j.configuration,则将字符串变量资源设置为其默认值"log4j.properties".
- 尝试将资源变量转换为URL.
- 如果资源变量无法转换为URL(例如由于MalformedURLException),则通过调用返回URL的org.apache.log4j.helpers.Loader.getResource(resource,Logger.class)从类路径中搜索资源. .请注意,字符串"log4j.properties"构成格式错误的URL.有关搜索位置的列表,请参阅Loader.getResource(java.lang.String).
因此,您需要预先file:添加log4j.configuration属性值,以便将其视为URL.
更好的代码:
System.setProperty("log4j.configuration", new File("resources", "log4j.xml").toURL());
Run Code Online (Sandbox Code Playgroud)
您可以设置VM参数: -Dlog4j.configuration='path_to_log4j.xml'
或以编程方式:
String logFilePath = new File(<path_to_log4j.xml>);
if (logFilePath == null || "".equalsIgnoreCase(logFilePath)) {
URL file = this.getClass().getResource(DEFAULT_CONF);
DOMConfigurator.configure(file);
} else {
DOMConfigurator.configure(<default_config_file>);
}
Run Code Online (Sandbox Code Playgroud)