如何为不同的appender配置log4j

时间:2013-12-06 10:05:30

标签: java logging log4j

我尝试为不同的输出层配置log4j.properties。

例如:

  • 仅在控制台上显示WARN级别。
  • 将INFO级别写入日志文件。

我试图找到正确的解决方案。我发现当你写一些关于你所需的包的信息级别时:

  

log4j.logger.your.package.name = DEBUG

它将调试记录器输出到控制台和文件。

此处log4j.properties的内容:

# Root logger option
log4j.rootLogger=WARN, stdout, file 

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.target=System.out 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.file=logs/myapp_test.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 

log4j.logger.com.my.lab=DEBUG
  • 如何为文件和控制台配置不同的输出层?

2 个答案:

答案 0 :(得分:1)

您可以为File&amp ;;设置不同的日志记录级别控制台Appender为

# Root logger option
log4j.rootLogger=INFO, stdout, file 

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.target=System.out 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.file=logs/myapp_test.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 


# Set the logger level of Console Appender to WARN
log4j.appender.stdout.Threshold = WARN

也可以参考this链接

答案 1 :(得分:1)

您可以定义一个阈值:

# Root logger option
log4j.rootLogger=INFO, stdout, file 

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold = WARN
log4j.appender.stdout.target=System.out 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.file=logs/myapp_test.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n 

log4j.logger.com.my.lab=DEBUG