2013-10-21 50 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