一、SSH在使用Log4j进行日志管理时常会遇到这个异常:
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
网上也有很多解决方案,我在此总结了一下,出现这个问题时应该按以下思路来排查:
1. 确保log4j的配置文件log4j.properties或log4j.xml已经存在(在classpath路径或其他路径下都行,文件内容可参考后面的内容)
2. 没有在web.xml中配置log4j的监听器,如果没有按以下方式配置:
<!-- log4j配置文件地址 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j/log4j.properties</param-value>
</context-param>
<!-- spring配置文件地址 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<!-- Log4j的监听器要放在spring监听器前面 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
注意:Log4j的监听器要放在spring监听器前面
3. 确保log4j.properties中没有明显的错误存在,如logger或appender配置有误
二、实践验证中的疑似小问题
经过上述几个步骤的排查和修改,日志输出应该没异常了,但实际运行中,还存在一个疑似的问题,就是设置输出到文件中的日志,同时在控制台也会输出,而控制台并没有设置相应的logger,log4j.properties配置如下:
log4j.rootLogger = WARN,C1
log4j.addivity.org.apache=true
#category
log4j.category.org.hibernate.tool.hbm2ddl =DEBUG,F1
log4j.category.org.hibernate.SQL =DEBUG,A1
#应用于控制台
log4j.appender.C1=org.apache.log4j.ConsoleAppender
#log4j.appender.C1.Threshold=WARNING
log4j.appender.C1.Target=System.out
#log4j.appender.C1.Encoding=UTF-8
log4j.appender.C1.layout=org.apache.log4j.PatternLayout
log4j.appender.C1.layout.ConversionPattern=[CONSOLE] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#每天建新日志
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=E:\\JavaEE workspace\\Spring\\logs\\log4j_daily.log
#log4j.appender.A1.Encoding=UTF-8
#log4j.appender.A1.Threshold=DEBUG
log4j.appender.A1.DatePattern=.yyyy-MM-dd
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L : %m%n
#应用于文件
log4j.appender.F1=org.apache.log4j.FileAppender
log4j.appender.F1.File=E:\\JavaEE workspace\\Spring\\logs\\Spring.log
log4j.appender.F1.Append=true
#log4j.appender.F1.Threshold=DEBUG
#log4j.appender.F1.Encoding=UTF-8
log4j.appender.F1.layout=org.apache.log4j.PatternLayout
log4j.appender.F1.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
操作数据库,有SQL输出到文件log4j_daily.log时,控制台也同样输出(控制台并没有这个logger的输出设置):
[CONSOLE] 2013-07-16 17:19:00,953 - org.hibernate.SQL -8235 [http-8080-2] DEBUG org.hibernate.SQL - select cat0_.id as id0_, cat0_.create_date as create2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother5_0_, cat0_.name as name0_ from tb_cat cat0_
Hibernate: select cat0_.id as id0_, cat0_.create_date as create2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother5_0_, cat0_.name as name0_ from tb_cat cat0_
不知这种情况算不算是正常。