javalogginglog4jlog4j2

Log4j2 Filter particular level in apender


What filter should I use to define particular level to be logged with appender? For example:

java:

LOGGER.debug("Debug message");
LOGGER.info("Info message");
LOGGER.warn("Warn message");
LOGGER.error("Error message");
LOGGER.fatal("Fatal message");

log4j2.xml:

<Configuration>
    <Appenders>
        <Console name="info-stdout-message">
            <PatternLayout pattern="[%logger{36}] %message %n" />
            <ThresholdFilter level="info"/>
        </Console>

        <Console name="detailed-stdout-message">
            <PatternLayout pattern="[%logger{36}] [%level] %message %n" />
        </Console>

        <File name="file-appender" fileName="logs/debug.log">
            <PatternLayout pattern="%d{HH:mm:ss dd.mm} [%t] [%-5level] %logger{36} - %msg %n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="file-appender" level="debug" />
            <AppenderRef ref="info-stdout-message" level="info"/>
            <AppenderRef ref="detailed-stdout-message" level="info"/>
        </Root>
    </Loggers>
</Configuration>

The file output is fine, but in console I have such result:

[application.Main] [INFO] Info message
[application.Main] Info message
[application.Main] [WARN] Warn message
[application.Main] Warn message
[application.Main] [ERROR] Error message
[application.Main] Error message
[application.Main] [FATAL] Fatal message
[application.Main] Fatal message

I need info-stdout-message appender to output only INFO messages, while detailed-stdout-message to output all except INFO. So, the console output should looks like:

[application.Main] Info message
[application.Main] [WARN] Warn message
[application.Main] [ERROR] Error message
[application.Main] [FATAL] Fatal message

I can't find out how to prevent filters respect level inheritance. Is it possible to do this?


Solution

  • This works:

    <Console name="info-stdout-message">
        <PatternLayout pattern="[%logger{36}] %message %n" />
        <Filters>
      
            <!-- Now deny warn, error and fatal messages -->
            <ThresholdFilter level="warn"  onMatch="DENY"   onMismatch="NEUTRAL"/>
    
            <!-- This filter accepts info, warn, error, fatal and denies debug/trace -->
            <ThresholdFilter level="info"  onMatch="ACCEPT" onMismatch="DENY"/>
        </Filters>
    </Console>