log4j在spring4中的配置

来源:互联网 发布:mac tomcat端口被占用 编辑:程序博客网 时间:2024/06/07 17:37

首先必须有日志配置文件


log4j.rootLogger = INFO,stdout,D,Elog4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%nlog4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = ${spring4.root}WEB-INF/logs/INFO.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = INFOlog4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

当然你愿意也可以用xml形式的


然后在把log4j配置到spring容器中

先说传统的web.xml形式的

<context-param>      <param-name>log4jConfigLocation</param-name>      <param-value>WEB-INF/conf/log4j.properties</param-value>  </context-param>
<context-param><param-name>webAppRootKey</param-name><param-value>cweb.root</param-value></context-param><context-param>      <param-name>log4jRefreshInterval</param-name>        <param-value>3000</param-value>   </context-param>    <listener>      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   </listener>  

log4jConfigLocation 是指明log4j配置文件位置  
webAppRootKey 指定一个项目路径的系统变量,相同容器中,不同项目不能一样,这样在log4j.properties指定日志文件路径可以指定到项目路径下,不再局限于绝对路径
log4jRefreshInterval 是log4j配置文件自动刷新时间
还有一个log4j的日志监听器

还有一种形式就是我最喜欢的纯java配置,

在程序初始化类中重载OnStartup

public class Spring4WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {// TODO Auto-generated method stubservletContext.addListener(Log4jConfigListener.class);servletContext.addListener(WebSessionListener.class);servletContext.setInitParameter("webAppRootKey", "spring4.root");servletContext.setInitParameter("log4jConfigLocation", "classpath:log4j.properties");servletContext.setInitParameter("log4jRefreshInterval", "10000");super.onStartup(servletContext);}


这里我要着重强调一下,使用webAppRootKey指定应用路径必须指定log4j.properties的位置,就算是默认位置也必须指定即配置log4jConfigLocation,否则系统变量无法应用到log4j中去;

还有Spring通过WebAppRootListener 这个监听器来运行时的项目路径,但是如果在web.xml中已经配置了Log4jConfigListener这个监听器,则不需要配置WebAppRootListener了。因为Log4jConfigListener已经包含了WebAppRootListener的功能

原创粉丝点击