log4j以不同的级别往不同文件(屏幕)打印日志的方法

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值