log4j为很完善的日志系统,通过设置配置文件来控制日志系统.可以自定义日志的输出级别,指定日志保存的方式(文件、数据库、邮件等),下面示例对控制台、文件的日志配置:
1) 把log4j.properties或是log4j.xml放在src根下(ClassPath路径中),或者结合spring的配置在web.xml中
> log4j.properties内容举例如下:
log4j.rootCategory=DEBUG, stdout, R
#Console config
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=<%d> <%-5p> <%c> - %m(%F:%M:%L)%n
#File config
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina_home}/logs/test.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=0
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=<%d> <%-5p> <%c> - %m(%F:%M:%L)%n
#Package config
log4j.logger.org.apple=DEBUG
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.springframework=ERROR
log4j.logger.org.apache.struts=ERROR
> log4j.xml内容举例如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%p - %C{1}.%M(%L) | %m%n"/>
</layout>
</appender>
<logger name="org.apache">
<level value="WARN"/>
</logger>
<logger name="net.sf.hibernate">
<level value="WARN"/>
</logger>
<logger name="org.springframework">
<level value="WARN"/>
</logger>
<logger name="org.apple">
<level value="DEBUG"/>
</logger>
<root>
<level value="WARN"/>
<appender-ref ref="CONSOLE"/>
</root>
</log4j:configuration>
2) 在需要做日志处理的类中,如下处理:
private static Log log = LogFactory.getLog(ClassName.class);