You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式过滤ThreadContextMap中的键值对?

解决方案

针对你需要用正则匹配ThreadContextMap中ENV值来过滤日志的需求,Log4j2的ThreadContextMapFilter本身不支持正则匹配,但可以通过以下两种方案实现:

方案一:使用ScriptFilter(快速实现)

Log4j2内置支持ScriptFilter,允许通过脚本语言编写自定义过滤逻辑,无需额外编码。以下是基于JavaScript的配置示例:

<Console name="prodOutput" target="SYSTEM_OUT">
    <PatternLayout pattern="..."/>
    <Filters>
        <ScriptFilter onMatch="DENY" onMismatch="NEUTRAL">
            <Script language="JavaScript">
                <![CDATA[
                    // 获取ThreadContext中的ENV值
                    var env = ThreadContext.get("ENV");
                    // 匹配prod或qa后跟一个及以上数字的格式
                    return env != null && /^(prod|qa)\d+$/.test(env);
                ]]>
            </Script>
        </ScriptFilter>
    </Filters>
</Console>

逻辑说明

  • 脚本会获取当前日志事件的ThreadContext中ENV的值,用正则^(prod|qa)\d+$匹配格式
  • 匹配成功时触发onMatch="DENY",过滤掉该日志;匹配失败时返回NEUTRAL,不影响后续过滤规则

方案二:自定义Java Filter(灵活扩展)

如果需要更复杂的逻辑或避免依赖脚本引擎,可以自定义一个Log4j2 Filter插件:

1. 编写自定义Filter类

import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import java.util.regex.Pattern;

@Plugin(name = "EnvRegexFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE)
public class EnvRegexFilter extends AbstractFilter {
    private final Pattern envPattern;

    private EnvRegexFilter(Pattern pattern, Result onMatch, Result onMismatch) {
        super(onMatch, onMismatch);
        this.envPattern = pattern;
    }

    @Override
    public Result filter(LogEvent event) {
        String env = event.getContextMap().get("ENV");
        if (env != null && envPattern.matcher(env).matches()) {
            return onMatch;
        }
        return onMismatch;
    }

    @PluginFactory
    public static EnvRegexFilter createFilter(
            @PluginAttribute("regex") String regex,
            @PluginAttribute("onMatch") Result onMatch,
            @PluginAttribute("onMismatch") Result onMismatch) {
        Pattern pattern = Pattern.compile(regex);
        return new EnvRegexFilter(pattern, onMatch, onMismatch);
    }
}

2. 在Log4j2配置中引用

<Console name="prodOutput" target="SYSTEM_OUT">
    <PatternLayout pattern="..."/>
    <Filters>
        <EnvRegexFilter regex="^(prod|qa)\d+$" onMatch="DENY" onMismatch="NEUTRAL"/>
    </Filters>
</Console>

逻辑说明

  • 自定义Filter通过Log4j2的插件注解注册,配置时直接指定正则表达式和匹配行为
  • 过滤逻辑与ScriptFilter一致,但更适合需要复用或扩展的场景

内容的提问来源于stack exchange,提问作者waffledood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:10:41