Log4J输出至当前web路径

经过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>
相关文章
相关标签/搜索