我们组以前一直习惯将log存放在项目根目录下的log目录中,相对比较好查看log. 这就要求log配置的路径是相对于项目根目录的相对路径.
1 log4j配置相对路径
我们使用sping获取项目的根路径.在web.xml中配置listener
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
Log4jConfigListener需要配置在ContextLoaderListener之前才能起到作用.
接下来,在log4j,properties文件中,就可以使用webapp.root表示项目根路径了.log4j.appender.error.File=${webapp.root}/log/error.log
log文件的位置为项目根路径下的log目录error.log
2 webapp.root在部署多个项目时的冲突问题
在实际项目中,当tomcat中部署了超过一个项目时,tomcat启动时会出现类似如下的错误.Exception sending context initialized event to listener instance of class org.springframework.web.util.Log4jConfigListener java.lang.IllegalStateException: Web app root system property already set to different value: 'webapp.root' = [XX] instead of [YY] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files! 这是由于webapp.root是作为System Property系统属性存在的,多个项目中都使用了listener就会产生冲突问题.解决的办法是在web.xml中定义webAppRootKey参数,以替换默认的webapp.root
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>test.root</param-value>
</context-param>
此时,在log4j.properties文件中即可按如下方式获取项目路径了
log4j.appender.error.File=${test.root}/log/error.log