2013-07-08 35 views
1

我使用log4j登錄我的應用程序。在每堂課我需要登錄的東西我有以下幾點:Log4j沒有看到.properties文件

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

log4j.properties放置到該文件夾​​/ src目錄/主/資源/

路徑/log4.properties由IDEA給出複製參考。當我啓動我的應用程序時,它顯示FileNotFoundException

+1

不要使用'FileInputStream',用你的'類#的getResourceAsStream()',因爲該文件是在classpath。你也不需要自己加載log4j屬性。 –

+0

如果我自己不加載log4j.properties,我會得到類似「log4j no config found。正確配置log4j」 –

+0

你在哪裏放置該文件? –

回答

4

請勿使用FileInputStream

java.io及其配置文件與當前工作目錄一起工作,即執行JVM的目錄而不是代碼工作區。

說明如果代碼從C:\TEMP執行該考慮下面的代碼段

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

,所述intemp.txt預計將在這種情況下的工作目錄(C:/TEMP)。如果不是這樣會拋出FileNotFoundException。文件名的路徑始終是絕對的而不是相對的。

爲了避免硬編碼,最好的方法是將所有必需的文件放在classpath中並使用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); 
1

log4j的,默認情況下,會查找log4j.properties文件中的類路徑中,所以您不需要使用類PropertyConfigurator,ONY如果文件沒有在classpath的根目錄中。

Spring MVC + Log4j Integration Example,您將看到:

enter image description here