1

我使用 log4j 登录我的应用程序。在每节课中,我都需要记录以下内容:

Properties props = new Properties();
    try {
        props.load(new FileInputStream("/log4j.properties"));
    } catch (Exception e){
        LOG.error(e);
    }
PropertyConfigurator.configure(props);

log4j.properties 放在文件夹 /src/main/resources/

IDEA 给出路径 /log4.properties 作为复制参考。当我启动我的应用程序时,它显示 FileNotFoundException

4

2 回答 2

4

不要使用FileInputStream.

及其关联使用java.io当前工作目录,即执行 JVM 的目录,而不是代码工作区。

为了说明这一点,请考虑以下代码

class ReadFrmFile {
    public static void main(String args[]) {
        FileInputStream fin = New FileInputStream("intemp.txt");
    }
}

如果代码是从 执行的C:\TEMP,在这种情况下intemp.txt,应该在工作目录(C:/TEMP)中。如果不是,这将抛出FileNotFoundException. 文件名的路径总是绝对的而不是相对的。

为了避免硬编码,最好的方法是将所有需要的文件放在类路径中并使用getResourceAsStream() 加载它们。

    Properties props = new Properties();
    try {
        InputStream inStream = **YOUR_CLASS_NAME**.class.getResourceAsStream("/log4j.properties");
        props.load(inStream);
    } catch (Exception e){
        LOG.error(e);
    }
    PropertyConfigurator.configure(props);
于 2013-07-08T13:32:09.740 回答
1

默认情况下,log4jlog4j.properties在类路径中查找文件,因此您不需要使用 class PropertyConfigurator,除非该文件不存在于类路径的根目录中。

Spring MVC + Log4j 集成示例中,您将看到:

在此处输入图像描述

于 2013-07-08T22:13:35.413 回答