使用log4j将不同的日志级别记录到不同的文件

时间:2012-09-17 13:11:21

标签: java logging log4j

我正在使用log4j登录我的应用程序。我正在尝试不同级别的日志在不同的文件,但出了点问题。有关此问题的任何帮助将受到高度赞赏。

    <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="console" class="org.apache.log4j.ConsoleAppender"> 
    <param name="Target" value="System.out"/> 
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> 
    </layout> 
</appender> 

<appender name="DEBUG" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="TCS_patch_9/log/retailer_debug.log" />
  <param name="Threshold" value="DEBUG" />
  <param name="MaxFileSize" value="2MB"/>
  <param name="MaxBackupIndex" value="3"/>
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{ISO8601} %-5p %c - %m%n"/>
  </layout>
</appender>

<appender name="INFO" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="TCS_patch_9/log/retailer_info.log" />
  <param name="Threshold" value="INFO" />
  <param name="MaxFileSize" value="2MB"/>
  <param name="MaxBackupIndex" value="3"/>
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{ISO8601} %-5p %c - %m%n"/>
  </layout>
</appender>
<appender name="ERROR" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="TCS_patch_9/log/retailer_error.log" />
  <param name="Threshold" value="ERROR" />
  <param name="MaxFileSize" value="2MB"/>
  <param name="MaxBackupIndex" value="3"/>
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{ISO8601} %-5p %c - %m%n"/>
  </layout>
</appender>
<appender name="FATAL" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="TCS_patch_9/log/retailer_repeat_delay.log" />
  <param name="Threshold" value="FATAL" />
  <param name="MaxFileSize" value="2MB"/>
  <param name="MaxBackupIndex" value="3"/>
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{ISO8601} %-5p %c - %m%n"/>
  </layout>
</appender>

  <root> 
    <priority value ="error" /> 
    <appender-ref ref="console"/> 
    <appender-ref ref="DEBUG"/> 
    <appender-ref ref="INFO"/> 
    <appender-ref ref="ERROR"/>
    <appender-ref ref="FATAL"/> 
  </root>

</log4j:configuration>

1 个答案:

答案 0 :(得分:5)

log4j appender的标准行为是它们将所有消息记录在其阈值级别或更高,即具有阈值INFO的appender将记录INFO,WARN,ERROR和FATAL消息,但不记录DEBUG。如果您只想记录 INFO消息但不记录WARN及以上you need to use a LevelMatchFilter

您还需要将根记录器优先级设置为DEBUG,否则它只会向其appender发送ERROR和FATAL消息,并且您的DEBUG和INFO文件将为空。