2013-10-21 48 views
0

我试图在Spring Web应用程序中手动加载log4j.properties(mylog4j.properties)文件。该文件位于/WEB-INF/,我读SYPLogger类文件,如下图所示:Log4j使用Java属性手动配置

private static final String CONF_FILE_NAME = "mylog4j.properties";    
Properties props = new Properties(); 
props.load(new FileInputStream(CONF_FILE_NAME)); 
PropertyConfigurator.configure(props); 

Project File Explorer

虽然我尝试不同的位置,我无法读取文件。当我给配置文件的完整路径时,一切都很好。但上面的代码给出了FileNotFoundException(系统找不到指定的文件)。 请帮忙。 在此先感谢。

回答

1

尝试下一个:

String path = Thread.currentThread() 
        .getContextClassLoader() 
        .getResource("/") 
        .toURI() 
        .resolve("../mylog4j.properties") 
        .getPath(); 
Properties props = new Properties(); 
props.load(new FileInputStream(path)); 
PropertyConfigurator.configure(props); 

以另一种方式,你见过类org.springframework.web.util.Log4jConfigListener。您可以在web.xml文件中配置此侦听器。例如:

<context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>/WEB-INF/mylog4j.properties</param-value> 
</context-param> 
<listener> 
    <listener-class> 
     org.springframework.web.util.Log4jConfigListener 
    </listener-class> 
</listener> 
+0

谢谢。我正在寻找第一个解决方案。 – Brucevilla