2011-04-07 111 views
16

使用log4j,我怎樣才能找出當前DOMConfigurator文件log4j.xml使用的名稱和路徑,使用PropertyConfigurator.configureAndWatch方法重置文件名,該方法需要該文件的名稱和路徑才能看到如果它改變了。log4j:使用哪個配置文件?

API文檔向我展示瞭如何配置log4j來重新加載配置,但是我找不到一種方法來查看自動獲取的文件名和路徑。 應用程序正在獨立運行,即任何應用程序服務器。

謝謝。

回答

21

恐怕你沒有機會從API中獲取自動拾取的路徑。正如我理解log4j的源代碼,檢測到的路徑將被使用,而不是被存儲。

至少你可以使用-Dlog4j.debug屬性輸出log4j的內部調試信息在啓動時,你會得到一些信息是這樣的:

log4j: Trying to find [log4j.xml] using context classloader [email protected] 
log4j: Using URL [file:/C:/develop/workspace/foobar/target/classes/log4j.xml] for automatic log4j configuration. 
log4j: Preferred configurator class: org.apache.log4j.xml.DOMConfigurator 

'log4j: Using URL ...'線來自LogManager類。您可以從這裏檢查初始化過程。正如我所看到的,該URL不會被存儲以備後用。

2

您可以使用與Log4j相同的進程在LogManager類的靜態初始化上使用。瞭解其他初始化和外部配置,例如來自Spring的org.springframework.web.util.Log4jConfigListener

public static URL getLog4jConfig() { 
    String override = OptionConverter.getSystemProperty("log4j.defaultInitOverride", null); 
    if (override == null || "false".equalsIgnoreCase(override)) { 
     String configurationOptionStr = OptionConverter.getSystemProperty("log4j.configuration", null); 

     URL url; 

     if (configurationOptionStr == null) { 
     url = Loader.getResource("log4j.xml"); 
     if (url == null) { 
      url = Loader.getResource("log4j.properties"); 
     } 
     } else { 
     try { 
      url = new URL(configurationOptionStr); 
     } catch (MalformedURLException ex) { 
      url = Loader.getResource(configurationOptionStr); 
     } 
     } 
     return url; 
    } else { 
     return null; 
    } 
    }