【问题标题】:Filter out messages matching two filters in Log4j2过滤掉与 Log4j2 中的两个过滤器匹配的消息
【发布时间】:2021-09-10 05:22:58
【问题描述】:

我正在运行一个使用log4j2.xml 配置日志记录的Java 应用程序。我想在消息中删除包含特定字符串的消息并且也有特定的 MDC 密钥。

如果我像这样在 MDC 上指定一个过滤器:

<ThreadContextMapFilter onMatch="DENY" onMismatch="NEUTRAL">
  <KeyValuePair key="someValue" value="foo"/>
</ThreadContextMapFilter>

它会正确删除所有具有此键值对的消息,但我需要它仅在 RegexFilter 也匹配时才删除这些消息。有没有办法做到这一点?我看到有CompositeFilter,但据我所知,它无法为我执行这种布尔运算。

我没有能力修改这个应用程序的源代码,我只能使用log4j2.xml

【问题讨论】:

  • CompositeFilter 中,当第一个过滤器返回 ACCEPT 或 DENAY 时,它会退出。因此,您无法进行 AND 过滤配置。唯一想到的是创建一个自定义过滤器,但是,从您编写的内容来看,这不是您的解决方案......

标签: java logging filter log4j2


【解决方案1】:

有两种方法可以实现您想要的。 (1) 如您在问题中提到的,使用RegexFilterThreadContextMapFilter 创建一个CompositeFilter。 (2) 使用ScriptFilter

以下是一些示例代码,用于说明如何同时执行这两项操作。 一、生成一些日志事件的类:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

public class SomeClass {

    private static final Logger log = LogManager.getLogger();   
    
    public static void main(String[] args){
        ThreadContext.put("someValue", "foo");
        log.info("Here's a test of info!"); //should not be accepted
        log.info("A message that doesn't match the regex"); //should be accepted
        ThreadContext.put("someValue", "bar");
        log.info("Another test of info"); //regex matches, context does not. Accepted.
        log.info("Some other message"); //does not match regex, context does not match. Accepted.
    }
}

现在是log4j2.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyy-MM-dd} [%t] %-5level %logger{36} %X{someValue} - %msg%n" />
        </Console>

        <File name="File1" fileName="logs/File1.log" immediateFlush="false"
            append="false">
            <PatternLayout
                pattern="%d{yyy-MM-dd} [%t] %-5level %logger{36} %X{someValue} - %msg%n" />
            <Filters>
                <ThreadContextMapFilter onMatch="NEUTRAL" onMismatch="ACCEPT">
                  <KeyValuePair key="someValue" value="foo"/>
                </ThreadContextMapFilter>
                <RegexFilter regex=".* test .*" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>

        </File>
        <File name="File2" fileName="logs/File2.log" immediateFlush="false"
            append="false">
            <PatternLayout
                pattern="%d{yyy-MM-dd} [%t] %-5level %logger{36} %X{someValue} - %msg%n" />
            <ScriptFilter onMatch="ACCEPT" onMisMatch="DENY">
              <Script name="MyFilter" language="JavaScript"><![CDATA[
                  if(logEvent.getContextMap().get("someValue") == "foo" 
                     && logEvent.getMessage().getFormattedMessage().matches(".* test .*")){
                        false
                    }else{
                        true
                    }
              ]]></Script>
            </ScriptFilter>
        </File>
    </Appenders>

    <Loggers>
        <Root level="ALL">
            <AppenderRef ref="Console"  />
            <AppenderRef ref="File1"  />
            <AppenderRef ref="File2"  />
        </Root>
    </Loggers>
</Configuration>

这里是控制台输出示例:

2021-09-24 [main] INFO  example.SomeClass foo - Here's a test of info!
2021-09-24 [main] INFO  example.SomeClass foo - A message that doesn't match the regex
2021-09-24 [main] INFO  example.SomeClass bar - Another test of info
2021-09-24 [main] INFO  example.SomeClass bar - Some other message

请注意,由于控制台附加程序没有过滤器,因此所有消息都被接受。

写入 File1 和 File2 的日志是相同的,示例输出如下:

2021-09-24 [main] INFO  example.SomeClass foo - A message that doesn't match the regex
2021-09-24 [main] INFO  example.SomeClass bar - Another test of info
2021-09-24 [main] INFO  example.SomeClass bar - Some other message

请注意已根据需要排除了正则表达式和上下文值匹配的 1 条消息。

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2020-09-22
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多