如何在spring-webflux WebFilter中正确使用slf4j MDC [英] How to correctly use slf4j MDC in spring-webflux WebFilter

查看:2274
本文介绍了如何在spring-webflux WebFilter中正确使用slf4j MDC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我引用了博客文章使用Reactor Context和MDC进行上下文记录但我不知道如何在WebFilter中访问reactor上下文。

I referenced with the blog post Contextual Logging with Reactor Context and MDC but I don't know how to access reactor context in WebFilter.

@Component
public class RequestIdFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        List<String> myHeader =  exchange.getRequest().getHeaders().get("X-My-Header");

        if (myHeader != null && !myHeader.isEmpty()) {
            MDC.put("myHeader", myHeader.get(0));
        }

        return chain.filter(exchange);
    }
}


推荐答案

你可以做类似于下面的事情,您可以使用您喜欢的任何类设置上下文,对于此示例我只使用了标题 - 但是自定义类可以正常运行。
如果你在这里设置,那么任何带有处理程序等的日志记录也可以访问上下文

logWithContext 在下面,设置MDC并在之后清除它。显然,这可以用你喜欢的任何东西代替。

You can do something similar to below, You can set the context with any class you like, for this example I just used headers - but a custom class will do just fine. If you set it here, then any logging with handlers etc will also have access to the context.
The logWithContext below, sets the MDC and clears it after. Obviously this can be replaced with anything you like.

public class RequestIdFilter  implements WebFilter {

    private Logger LOG = LoggerFactory.getLogger(RequestIdFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        return chain.filter(exchange)
                .doAfterSuccessOrError((r, t) -> logWithContext(headers, httpHeaders -> LOG.info("Some message with MDC set")))
                .subscriberContext(Context.of(HttpHeaders.class, headers));
    }

    static void logWithContext(HttpHeaders headers, Consumer<HttpHeaders> logAction) {
        try {
            headers.forEach((name, values) -> MDC.put(name, values.get(0)));
            logAction.accept(headers);
        } finally {
            headers.keySet().forEach(MDC::remove);
        }

    }

}

这篇关于如何在spring-webflux WebFilter中正确使用slf4j MDC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆