您的位置:首页 > 其它

Log4J输出至当前web路径

2012-11-10 02:17 841 查看
通过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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  log4j 输出路径