specific logger for levels

2019-04-10 15:46发布

I am using log4j for logging. I have a scenario where I have to use seperate logging for different severity. For example, for package foo I have to print messages with severity ERROR in the console whereas I have to print messages with severity WARN in log file. How can I configure my log4j.xml for the same.

标签: log4j
1条回答
老娘就宠你
2楼-- · 2019-04-10 15:53

You may use LevelMatchFilter for your task. Also you should not forget to use another filter - DenyAllFilter - as the last filter in the chain of filters.

Your log4j.xml will look like this:

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.SimpleLayout" />
        <filter class="org.apache.log4j.varia.LevelMatchFilter">
            <param name="LevelToMatch" value="ERROR" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
        <filter class="org.apache.log4j.varia.DenyAllFilter" />     
    </appender>

    <appender name="fileAppender" 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="WARN" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
        <filter class="org.apache.log4j.varia.DenyAllFilter" />     
    </appender>

    <logger name="foo">
         <level value="WARN" />
         <appender-ref ref="consoleAppender" />
         <appender-ref ref="fileAppender" />
    </logger>
</log4j:configuration>
查看更多
登录 后发表回答