FROM: http://space.baidu.com.cn/jadmin/blog/item/c734ab58a159c6d79c8204b0.html
Spring提供了一个很实用的工具,可以让Web应用灵活配置log4j,这个工具类是:
org.springframework.web.util.Log4jConfigListener
org.springframework.web.util.Log4jConfigServlet
由于:
Note that this class has been deprecated for containers implementing
Servlet API 2.4 or higher, in favor of{@linkLog4jConfigListener}.</i><br>
According to Servlet 2.4, listeners must be initialized before load-on-startup
servlets. Many Servlet 2.3 containers already enforce this behavior
(see ContextLoaderServlet javadocs for details). If you use such a container,
this servlet can be replaced with Log4jConfigListener.
建议使用org.springframework.web.util.Log4jConfigListener,而非org.springframework.web.util.Log4jConfigServlet,下面来说下Log4jConfigListener的用法:
其实很简单,只要在web.xml文件中配置相关参数和注册此监听器即可,下面是相应的配置片段:
<!-- 配置log4j配置文件的路径,可以是xml或 properties文件(此参数必须配)-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
<!-- 每隔多少毫秒扫描一下配置文件的变化(此参数可选配) -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<!-- spring框架默认定义webAppRootKey的值为webapp.root,若不配此参数默认值就是webapp.root(因此,此参数可选配) -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webName.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
这样就可以在log4j的配置中如下进行了:
#log4j.rootLogger=INFO,A1,R
#log4j.rootLogger=DEBUG,A1,R
log4j.rootLogger=DEBUG,consApp,logApp,ErrorLog
log4j.appender.consApp=org.apache.log4j.ConsoleAppender
log4j.appender.consApp.layout=org.apache.log4j.PatternLayout
log4j.appender.consApp.layout.ConversionPattern=[%p] %l %d{yyyy-MM-dd HH:mm:ss} %m%n
# Define all the appenders
log4j.appender.logApp=org.apache.log4j.DailyRollingFileAppender
#use web.xml <param-value>==>webName.root
log4j.appender.logApp.File=${webName.root}/WEB-INF/logs/log.log
log4j.appender.logApp.Append=true
log4j.appender.logApp.Encoding=UTF-8
# Roll-over the log once per day
log4j.appender.logApp.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.logApp.layout = org.apache.log4j.PatternLayout
log4j.appender.logApp.layout.ConversionPattern =[%p] %l %d{yyyy-MM-dd HH:mm:ss} %m%n
## ERROR LOG
log4j.appender.ErrorLog=org.apache.log4j.RollingFileAppender
##定义只有error级别输出的到此文件,webName.root其实是webRoot目录
log4j.appender.ErrorLog.File=${webName.root}/WEB-INF/logs/error.log
log4j.appender.ErrorLog.Append = true
log4j.appender.ErrorLog.Threshold =ERROR
log4j.appender.ErrorLog.MaxFileSize=2048KB
log4j.appender.ErrorLog.MaxBackupIndex=20
log4j.appender.ErrorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.ErrorLog.layout.ConversionPattern =[%p] %l %d{yyyy-MM-dd HH:mm:ss} %m%n