經過Spring提供的一個類,能夠輔助log4j配置文件將日誌文件輸出至應用程序的相對路徑
這個類是
org.springframework.web.util.Log4jConfigListener
這個類經過監聽器將應用程序的路徑設到System的property裏,從而能夠將表明應用程序路徑的property做爲log4j的輸出路徑
log4j.appender.R.File=${webapp.root}/log/log.log
source code :
public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";//web.xml的context-param
public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";//web.xml默認的context-key
String root = servletContext.getRealPath("/");//獲取應用程序路徑
......
String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);//根據context-param獲取context-key
String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);//context-key便是那個變量表明應用程序路徑
......
System.setProperty(key, root);//將context-key和應用程序路徑保存至System的property裏
要使用當前web路徑,只須要在web.xml配置一個監聽器便可
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
(注意:此監聽器要在Spring容器context配置以前,不然不起做用,由於加載ContextLoaderListener時,系統尚未加載Log4jConfigListener,因此不會去找log4j.property,因此監聽器必定要在Spring容器啓動前)
經過此監聽器,log4j的配置文件便可使用webapp.root日誌文件的輸出目錄
默認是web路徑是webapp.root,也能夠經過如下web.xml配置指定
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>xxx.xxx</param-value>
</context-param>