一直以来,我都以为Log4j仅能配置输出日志的最低等级,不能限定只输出某一/某些特定等级,今天,无意中发现了其实是可以的. 先上一份普通的log4j.properties

log4j.rootLogger=INFO, Console, File

###### Console appender definition #######
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %x %-5p [%c{3}] %m%n

###### File appender definition #######
log4j.appender.File=org.apache.log4j.DailyRollingFileAppender
log4j.appender.File.File=alfresco.log
log4j.appender.File.Append=true
log4j.appender.File.DatePattern='.'yyyy-MM-dd
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n

现在需要定义一个名为File2的appender ,仅记录INFO和ERROR,哈哈,有请Log4j的Filter

log4j.appender.File2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.File2.File=alfresco2.log
log4j.appender.File2.Append=true
log4j.appender.File2.DatePattern='.'yyyy-MM-dd
log4j.appender.File2.layout=org.apache.log4j.PatternLayout
log4j.appender.File2.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n

#配置Filter
#定义id为F1的拦截器,只接受INFO到ERROR
log4j.appender.File2.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.File2.filter.F1.LevelMin=INFO
log4j.appender.File2.filter.F1.LevelMax=ERROR
#定义id为F2的拦截器,不接受WARN
log4j.appender.File2.filter.F2=org.apache.log4j.varia.LevelMatchFilter
log4j.appender.File2.filter.F2.levelToMatch=WARN
log4j.appender.File2.filter.F2.acceptOnMatch=false
#可以继续定义你需要的拦截器F3/F4.....

通过定义不同组合的LevelRangeFilter/LevelMatchFilter,让特定的appender只记录你需要的log等级,非常方便的!

详细参考,请查阅Log4j:

JavaDoc Filter PropertyConfigurator



blog comments powered by Disqus

Published

2010-12-20 12:18:12

Categories


Tags

Fork me on GitHub