Search code examples
loggingfilterlog4jlog4j2

How to omit DEBUG logs after changing log level of a logger from INFO to DEBUG before sending to an appender in log4j2


I have a third party logger(audit-events) that is logging in INFO level. I want to convert these logs into DEBUG level and then omit them in stdout. Following is the code I wrote.

<AsyncLogger name="audit-events" level="${env:LOGGING_LEVEL:-INFO}" additivity="false">
     <AppenderRef ref="stdout-rewrite-info-to-debug"/>
</AsyncLogger>
<Rewrite name="stdout-rewrite-info-to-debug">
     <AppenderRef ref="stdout"/>
     <LoggerNameLevelRewritePolicy logger="audit-events">
          <KeyValuePair key="INFO" value="DEBUG"/>
     </LoggerNameLevelRewritePolicy>
     <Filters>
          <ThresholdFilter level="${env:LOGGING_LEVEL:-INFO}" onMatch="ACCEPT" onMismatch="DENY"/>
     </Filters>
</Rewrite>

${env:LOGGING_LEVEL:-INFO} is a value that is injected at application startup. (e.g.- INFO, DEBUG) Default value would be INFO if it is not injected.

The log level conversion works fine. The problem is if I injected the LOGGING_LEVEL value as INFO, I shouldn't be getting any DEBUG logs in stdout but here I am getting the converted DEBUG logs. I thought the filter would do the trick and omit them but for some reason it didn't. What am I doing wrong here?


Solution

  • Filtering in an Appender is performed before the Appender#append call. In the case of the RewriteAppender this means that the filter is applied before you modify the level of the event.

    You need to put the filter further down the appender pipeline:

    <Rewrite name="stdout-rewrite-info-to-debug">
         <AppenderRef ref="stdout" level="${env:LOGGING_LEVEL:-INFO}"/>
         <LoggerNameLevelRewritePolicy logger="audit-events">
              <KeyValuePair key="INFO" value="DEBUG"/>
         </LoggerNameLevelRewritePolicy>
    </Rewrite>