Java log4j 无法读取配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6528287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:41:13  来源:igfitidea点击:

log4j Could not read configuration file

javalog4j

提问by rottmanj

I am adding logging to a java web project I am working on. I have run into an error that I am unable to figure out.

我正在将日志记录添加到我正在处理的 Java Web 项目中。我遇到了一个我无法弄清楚的错误。

The error I am getting from tomcat is:
log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (No such file or directory)

我从 tomcat 得到的错误是:
log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (No such file or directory)

I have this simple method in my class:

我的课上有这个简单的方法:

@RemotingInclude
public UserAccount save(UserAccount dataObject)
{
    PropertyConfigurator.configure("log4j.properties");
    logger.debug(dataObject.toString());

    return dao.save(dataObject);
}

When I look in my webapps//WEB-INF/class folder I do see my log4j.properties file. When I deploy to my tomcat server and restart tomcat, I do see my admin.log file created, but nothing is written to it. Even after hitting the method above. Any help with this is greatly appreciated.

当我查看我的 webapps//WEB-INF/class 文件夹时,我确实看到了我的 log4j.properties 文件。当我部署到我的 tomcat 服务器并重新启动 tomcat 时,我确实看到我的 admin.log 文件已创建,但没有写入任何内容。即使在点击上面的方法之后。非常感谢您对此的任何帮助。

This is the current contents of my log4j.properties file:

这是我的 log4j.properties 文件的当前内容:

log4j.appender.AdminFileAppender=org.apache.log4j.FileAppender
log4j.appender.AdminFileAppender.File=admin.log
log4j.appender.AdminFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AdminFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n.
log4j.appender.ReportFileAppender=org.apache.log4j.FileAppender
log4j.appender.ReportFileAppender.File=report.log
log4j.appender.ReportFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ReportFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
log4j.logger.com.rottmanj.services=WARN,AdminFileAppender

采纳答案by Alfredo Osorio

That approach of bootstraping the Log4j is wrong. This is usually the way that is implemented:

这种引导 Log4j 的方法是错误的。这通常是实现的方式:

import org.apache.log4j.Logger;

public class MyService {

    public UserAccount save(UserAccount dataObject) {
        logger.debug(dataObject.toString());

        return dao.save(dataObject);

    }

    private static Logger logger = Logger.getLogger(MyService.class);

}

This way Log4j will automatically lookup for the log4j.properties in the root of the classpath.

这样 Log4j 将自动在类路径的根目录中查找 log4j.properties。