配置log4j.properties以将错误输出到文件

时间:2014-08-09 18:07:41

标签: logging log4j

我有多个java类,并希望将调试和错误输出写入不同的日志文件以及不同的位置。如何使用log4j.properties实现这一目标?

1 个答案:

答案 0 :(得分:0)

您需要过滤消息。但是,过滤器仅可通过XML配置文件log4j.xml获得。

  • org.apache.log4j.varia.LevelRangeFilter

    如果要指定appender的较低范围和较高范围:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN"
                                         "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
        <!-- DEBUG appender -->
        <appender name="DEBUGFILE" class="org.apache.log4j.FileAppender">
            <param name="file" value="debug.log" />
            <layout class="org.apache.log4j.SimpleLayout" />
            <filter class="org.apache.log4j.varia.LevelRangeFilter">
                <param name="LevelMin" value="DEBUG" />
                <param name="LevelMax" value="DEBUG" />
            </filter>
        </appender>
    
        <!-- ERROR appender -->
        <appender name="ERRORFILE" class="org.apache.log4j.FileAppender">
            <param name="file" value="error.log" />
            <layout class="org.apache.log4j.SimpleLayout" />
            <filter class="org.apache.log4j.varia.LevelRangeFilter">
                <param name="LevelMin" value="ERROR" />
                <param name="LevelMax" value="ERROR" />
            </filter>
        </appender>
    
        <!-- root -->
        <root>
            <priority value="ALL" />
            <appender-ref ref="DEBUGFILE" />
            <appender-ref ref="ERRORFILE" />
        </root>
    
    </log4j:configuration>
    
  • org.apache.log4j.varia.LevelMatchFilter

    如果您想过滤单个级别:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN"
                                         "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
        <!-- DEBUG appender -->
        <appender name="DEBUGFILE" class="org.apache.log4j.FileAppender">
            <param name="file" value="debug.log" />
            <layout class="org.apache.log4j.SimpleLayout" />
            <filter class="org.apache.log4j.varia.LevelMatchFilter">
                <param name="levelToMatch" value="DEBUG" />
            </filter>
        </appender>
    
        <!-- ERROR appender -->
        <appender name="ERRORFILE" class="org.apache.log4j.FileAppender">
            <param name="file" value="error.log" />
            <layout class="org.apache.log4j.SimpleLayout" />
            <filter class="org.apache.log4j.varia.LevelMatchFilter">
                <param name="levelToMatch" value="ERROR" />
            </filter>
        </appender>
    
        <!-- root -->
        <root>
            <priority value="ALL" />
            <appender-ref ref="DEBUGFILE" />
            <appender-ref ref="ERRORFILE" />
        </root>
    
    </log4j:configuration>