How to log warn only in log4j

一笑奈何 提交于 2020-05-29 11:26:23

问题


In Struts 2 application we use log4j for logging. I want to log only warn but when i try to use in my log4j.properties

log4j.rootLogger=warn, stdout

it prints error and fatal log too. I want only warn log. I read the levels of log in some tutorials. So I know why error and fatal prints, because they are less priority than warn. How to print warn log only in my console?

My Java code:

import org.apache.log4j.Logger;

public class LogClass {

    private static final org.apache.log4j.Logger log = Logger.getLogger(LogClass.class);

    public static void main(String[] args) {
            log.trace("Trace");
            log.debug("Debug");
            log.info("Info");
            log.warn("Warn");
            log.error("Error");
            log.fatal("Fatal");
    }
}

Any help will be greatly appreciated!


回答1:


Use the org.apache.log4j.varia.LevelRangeFilter filter. Your XML configuration file could be:

<?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>

For more options go here.

It looks like properties file configuration does not support filters. The following is taken from log4j's official wiki:

Filter is not supported by PropertiesConfigurator.

EDIT: Added console appender as well to the XML and turned off debug for log4j. Now it should go to both file and console.



来源:https://stackoverflow.com/questions/26052623/how-to-log-warn-only-in-log4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!