log4j的官方FAQ中其实已经给出非常好的解决方案,简单有效。
Is it possible to direct log output to different appenders by level?
Yes it is. Setting the Threshold option of any appender extending AppenderSkeleton, (most log4j appenders extend AppenderSkeleton) to filter out all log events with lower level than the value of the threshold option.For example, setting the threshold of an appender to DEBUG also allow INFO, WARN, ERROR and FATAL messages to log along with DEBUG messages. This is usually acceptable as there is little use for DEBUG messages without the surrounding INFO, WARN, ERROR and FATAL messages. Similarly, setting the threshold of an appender to ERROR will filter out DEBUG, INFO and WARN messages but not ERROR or FATAL messages.
This policy usually best encapsulates what the user actually wants to do, as opposed to her mind-projected solution.
See examples/sort4.lcf for an example threshold configuration.
If you must filter events by exact level match, then you can attach a LevelMatchFilter to any appender to filter out logging events by exact level match.
就是使用Threshold参数就行,threshold会过滤掉指定界别以下的所有日志。
如果需要精确匹配日志级别,FAQ也给出了方案,就是使用LevelMatchFilter。
下面是我自己的项目中使用的配置,屏幕上只打印INFO级别及以上日志,文件中打印DEBUG级别及以上的日志。
# Root logger option
log4j.rootLogger=DEBUG, file, stdout
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=E:..\\log\\test.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %t %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.threshold = INFO
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %t %m%n