如何在日志文件中仅获取特定级别的消息?

时间:2015-08-21 03:15:05

标签: java logging logback

我正在尝试将日志写入两个文件,在一个文件中我可以获取任何级别的日志,而在其他文件中我只查找INFO级别。这可能吗?

<configuration>
    <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
        <file>c:/log/myLogFile.log</file>
        <append>true</append>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
        <encoder>
            <pattern>%d [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="EVENTS_FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>c:/log/myLogFile-event.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>../logs/cweo-app-event-%i.log.gz</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>30</maxIndex>
        </rollingPolicy>

        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>100MB</maxFileSize>
        </triggeringPolicy>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <!-- <logger name="event" level="DEBUG"> <appender-ref ref="EVENTS_FILE" 
        /> </logger> -->
    <root>
        <appender-ref ref="fileAppender" />
        <appender-ref ref="EVENTS_FILE" />
    </root>

这是我的logback.xml EVENTS_FILE我只想打印INFO条消息。

1 个答案:

答案 0 :(得分:3)

请勿使用ThresholdFilter,请使用LevelFilter

LevelFilter不同,

ThresholdFilter提供了相等性测试。见Filters.

在这种情况下:

<appender name="EVENTS_FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>c:/log/myLogFile-event.log</file>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
      <level>INFO</level>
      <onMatch>ACCEPT</onMatch>
      <onMismatch>DENY</onMismatch>
    </filter>