Log4J输出至当前web路径

徘徊边缘 提交于 2020-03-01 03:37:51
通过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>



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!