更改log4j日志级别而不重启服务器

目的:服务器运行时修改log4j的输出级别后,不需要重启服务器。



        项目上线了后,我们生产环境一般设置的输出级别都是INFO,但是有些问题不一定能通过INFO信息找到。如何能做到 动态的修改日志的级别,而且不用重启服务,对线上环境的影响减少到最小呢?



首先POM中加上这些依赖:

  
  	
			3.2.2.RELEASE
	
  
  
  
		
			org.slf4j
			slf4j-api
			1.6.2
		

		
			org.slf4j
			slf4j-log4j12
			1.6.2
		
		
		
		
			javax.servlet
			servlet-api
			2.5
		
		
		
			log4j
			log4j
			1.2.16
		
		
		
		
			org.springframework
			spring-web
			${spring_version}
		
		
  

然后在项目的web.xml中加上:

  	log4jConfigLocation/WEB-INF/classes/log4j.propertieslog4jRefreshInterval6000org.springframework.web.util.Log4jConfigListener
		

log4jRefreshInterval  的作用是6000表示 开一条watchdog线程每6秒扫描一下配置文件的变化; 

最后附上log4j properties:

#log4j.rootLogger = [ level ] , appenderName, appenderName, ...
log4j.rootLogger = ERROR, console, dailyFile
#level=INFO,all can be output
#console is set to be a ConsoleAppender
log4j.appender.console = org.apache.log4j.ConsoleAppender
#console have four patterns
#org.apache.log4j.HTMLLayout
#org.apache.log4j.PatternLayout
#org.apache.log4j.SimpleLayout
#org.apache.log4j.TTCCLayout

log4j.appender.console.layout = org.apache.log4j.PatternLayout
#define the output type
log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
#file is set to output to a extra file
log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender
#the absolute route of the log4j file
#log4j.appender.dailyFile.File = /tmp/smarthome/base-web
log4j.appender.dailyFile.File = D:\\base-web.log
log4j.appender.dailyFile.Append=true
log4j.appender.dailyFile.layout=org.apache.log4j.PatternLayout  
log4j.appender.dailyFile.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
log4j.appender.dailyFile.Threshold=INFO
log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd'.log'


测试代码下载链接


你可能感兴趣的:(Log4j)