log4j在spring4中的配置

首先必须有日志配置文件


log4j.rootLogger = INFO,stdout,D,E

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${spring4.root}WEB-INF/logs/INFO.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

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


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

先说传统的web.xml形式的

  
    log4jConfigLocation  
    WEB-INF/conf/log4j.properties  

	webAppRootKey
	cweb.root

  
    log4jRefreshInterval  
      3000  
   
  
  
    org.springframework.web.util.Log4jConfigListener  
   

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


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

在程序初始化类中重载OnStartup

public class Spring4WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// TODO Auto-generated method stub
		servletContext.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的功能

你可能感兴趣的:(spring)