【笔记】Log4j 只打印一种级别的日志

发表于2017-01-18   630次阅读

比如只打印 warn 级别日志,而不打印 error 级别的日志,可以用 org.apache.log4j.varia.LevelRangeFilter 进行过滤。代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
    debug="false">

    <appender name="warn-out" class="org.apache.log4j.FileAppender">
        <param name="File" value="warn.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMax" value="warn" />
            <param name="LevelMin" value="warn" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMax" value="warn" />
            <param name="LevelMin" value="warn" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <root>
        <level value="warn" />
        <appender-ref ref="warn-out" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

官方文档参考这里:https://wiki.apache.org/logging-log4j/LogToAppenderByLevel