【发布时间】:2011-09-12 15:46:54
【问题描述】:
我想将我所有的配置文件放在我的应用程序目录的 /config 子文件夹中。 Log4j 期待我的应用程序根文件夹中的 log4j.properties 文件。有没有办法告诉 log4j 在哪里寻找属性文件?
【问题讨论】:
我想将我所有的配置文件放在我的应用程序目录的 /config 子文件夹中。 Log4j 期待我的应用程序根文件夹中的 log4j.properties 文件。有没有办法告诉 log4j 在哪里寻找属性文件?
【问题讨论】:
是的,定义log4j.configuration属性
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
注意,该属性值必须是 URL。
更多信息请阅读Log4j manual 中的“默认初始化过程”部分。
【讨论】:
ava -Dlog4j.configuration=file:/path/to/log4j.properties myApp放在哪里?我正在使用日食。我的log4j.properties 文件位于src/resources。
installation scripts、分期和产品问题的信息。我想亲自动手。陈奎。
您可以使用PropertyConfigurator 将 log4j.properties 加载到磁盘中的任何位置。
例子:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
如果您有 XML Log4J 配置,请改用 DOMConfigurator。
【讨论】:
使用 PropertyConfigurator:PropertyConfigurator.configure(configFileUrl);
【讨论】:
请参阅此示例,取自 - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
更改记录器级别 - Logger.getRootLogger().setLevel(Level.INFO);
【讨论】:
在 Eclipse 中,您可以将 VM 参数设置为:
-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}
【讨论】:
这是我的课程:路径很好,属性已加载。
package com.fiserv.dl.idp.logging;
import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggingCapsule {
private static Logger logger = Logger.getLogger(LoggingCapsule.class);
public static void info(String message) {
try {
String configDir = System.getProperty("config.path");
if (configDir == null) {
throw new MissingResourceException("System property: config.path not set", "", "");
}
Properties properties = new Properties();
properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
PropertyConfigurator.configure(properties);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(message);
}
public static void error(String message){
System.out.println(message);
}
}
【讨论】:
您必须像这样使用log4j.configuration 属性:
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
如果文件在类路径下(在 ./src/main/resources/ 文件夹内),您可以省略 file:// 协议:
java -Dlog4j.configuration=path/to/log4j.properties myApp
【讨论】: