How to log warn only in log4j

2019-07-21 03:43发布

问题:

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.