将错误记录到 stderr 和调试,将信息记录到 stdout 与 log4j

2022-08-31 16:11:01

我想使用apache log4j将日志记录添加到我正在开发的应用程序中。此时,我想将级别 INFO 和更低级别(TRACE、DEBUG)的所有日志消息重定向到 stdout,并将所有其他日志消息从 WARN 及以上(错误、致命)重定向到 stderr。例如:

...
logger.info("Processing at some point"); // must be written to stdout
logger.debug("Point x was processed"); // must be written to stdout
logger.warn("Incorrect point config"); // must be written only to stderr
logger.error("Exception occurred at point x"); // must be written only to stderr

那么我的log4j.properties文件应该是什么?以下是它如何看待这个妈妈:

log4j.rootLogger=DEBUG, stdout, stderr

# configure stdout
# set the conversion pattern of stdout
# Print the date in ISO 8601 format
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold = DEBUG
log4j.appender.stdout.Target   = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n

# configure stderr
# set the conversion pattern of stdout
# Print the date in ISO 8601 format
log4j.appender.stderr = org.apache.log4j.ConsoleAppender
log4j.appender.stderr.Threshold = WARN
log4j.appender.stderr.Target   = System.err
log4j.appender.stderr.layout = org.apache.log4j.PatternLayout
log4j.appender.stderr.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n

上述配置的问题在于 logger.error() ...也打印在标准输出。


答案 1

在下面也以属性文件格式解决。诀窍是获得正确的过滤器定义。Log4j 属性信息在这里

最初的尝试,修改为过滤WARN和错误:

log4j.rootLogger=TRACE, stdout, stderr

# configure stdout
# set the conversion pattern of stdout
# Print the date in ISO 8601 format
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold = TRACE
log4j.appender.stdout.Target   = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n
log4j.appender.stdout.filter.filter1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.stdout.filter.filter1.levelMin=TRACE
log4j.appender.stdout.filter.filter1.levelMax=INFO

# configure stderr
# set the conversion pattern of stdout
# Print the date in ISO 8601 format
log4j.appender.stderr = org.apache.log4j.ConsoleAppender
log4j.appender.stderr.Threshold = WARN
log4j.appender.stderr.Target   = System.err
log4j.appender.stderr.layout = org.apache.log4j.PatternLayout
log4j.appender.stderr.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n

答案 2

Per Jon Skeet在Post的上一篇文章

不幸的是,没有最大阈值,因此无论您在哪里收到调试消息,您也会收到警告消息。这有点痛苦,IMO。


推荐