Log4j学习笔记(2)_log4j配置示例&Spring集成log4j

时间:2022-02-21 21:53:31

log4j配置示例

#定义根日志级别和输出端(定义了两个输出端)
log4j.rootLogger=ERROR,CONSOLE,Orclight

#定义第一个输出端,输出到控制台
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %-5p %c(%L) - %m%n

#定时第二个输出端,输出到文件,该文件最大空间为1000KB,超过1000KB后自动备份,生成新文件
log4j.appender.Orclight=org.apache.log4j.RollingFileAppender
log4j.appender.Orclight.file=orclight.log
log4j.appender.Orclight.layout=org.apache.log4j.PatternLayout
log4j.appender.Orclight.layout.conversionPattern=%d [%t] %-5p %c(%L) - %m%n
log4j.appender.Orclight.MaxFileSize=1000KB
log4j.appender.Orclight.MaxBackupIndex=10

#定义具体某个包下的日志输出级别
log4j.logger.com.orclight.rbac=INFO,Orclight,CONSOLE
log4j.logger.com.orclight.rbac.services.impl.CacheServiceImpl=INFO,Orclight
log4j.logger.org.springframework=ERROR,Orclight

log4j.logger.org.springframework.jdbc.support=INFO
log4j.logger.org.springframework.scheduling=INFO
#定义sql语句的输出级别
log4j.logger.java.sql.Connection=DEBUG

# Struts OgnlUtil issues unimportant warnings
log4j.logger.com.opensymphony.xwork2.util.OgnlUtil=ERROR
log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=ERROR

在Spring中集成log4j

在web应用中为Spring配置log4j
  Spring的做法是使用一个Servlet Listener,在Web Container启动时把ROOT的绝对路径写到系统变量里,这样log4j的配置文件里就可以用${myAppfuse.root}来表示刚刚设进去的系统变量:log4j.appender.logfile.File=${myAppfuse.root}/logs/mylog.log
在Web.xml中配置语句如下:


<context-param> 
<param-name>webAppRootKey</param-name>
<param-value>myappfuse.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!--这里配置了一个listener,也可以配置servlet:-->
<!--
<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>
org.springframework.web.util.Log4jConfigServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->