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

Spring Sleuth 2.0记录MDC方法咨询及Spring Cloud 2.0适配问题

在Spring Cloud 2.x中自定义Sleuth MDC内容的解决方案

我明白你遇到的问题——Spring Cloud 2.x里原来的SpanLogger/Slf4jSpanLogger确实已经被移除,而且Slf4jCurrentTraceContext又被标记为final没法直接子类化,想要把配置的baggage和propagation keys放进MDC确实得换个思路。下面给你两种可行的方案,从简单到自定义:

方案一:用内置配置快速实现(推荐)

Spring Cloud Sleuth 2.x其实已经内置了把自定义baggage同步到MDC的能力,你只需要在配置里多加一行白名单配置就行:

首先,你已经配置了:

spring.sleuth.baggage-keys=user-id,request-id
spring.sleuth.propagation-keys=user-id,request-id

然后添加MDC白名单配置,指定哪些baggage键要同步到MDC:

spring.sleuth.log.slf4j.whitelisted-mdc-keys=user-id,request-id

这样默认的Slf4jCurrentTraceContext就会自动把这些白名单里的baggage键值对同步到MDC中,不需要写任何代码,这是最省心的方式。

方案二:自定义逻辑扩展(适合复杂场景)

如果你的需求更复杂,比如需要对baggage值做转换、或者有特殊的MDC处理逻辑,那可以通过自定义CurrentTraceContext的Scope装饰器来实现,不需要子类化Slf4jCurrentTraceContext——它的Builder支持添加自定义装饰器:

创建一个配置类,自定义CurrentTraceContext Bean:

import brave.propagation.CurrentTraceContext;
import brave.propagation.TraceContext;
import brave.slf4j.Slf4jCurrentTraceContext;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomSleuthMdcConfig {

    @Bean
    public CurrentTraceContext currentTraceContext() {
        return Slf4jCurrentTraceContext.newBuilder()
                // 添加自定义的Scope装饰器,处理MDC同步
                .addScopeDecorator(new BaggageToMdcDecorator())
                .build();
    }

    static class BaggageToMdcDecorator implements CurrentTraceContext.ScopeDecorator {
        @Override
        public CurrentTraceContext.Scope decorateScope(TraceContext context, CurrentTraceContext.Scope scope) {
            // 当TraceContext激活时,把需要的baggage放入MDC
            if (context != null) {
                // 读取配置的baggage键,这里可以根据实际配置动态获取,或者写死
                String userId = context.baggageItem("user-id");
                if (userId != null) {
                    MDC.put("user-id", userId);
                }
                String requestId = context.baggageItem("request-id");
                if (requestId != null) {
                    MDC.put("request-id", requestId);
                }
            }

            // 当Scope关闭时,清理MDC中的对应键
            return () -> {
                MDC.remove("user-id");
                MDC.remove("request-id");
                scope.close();
            };
        }
    }
}

这个装饰器会在TraceContext的Scope创建和销毁时,手动处理baggage与MDC的同步,完全满足自定义需求。

注意事项

  • 确保你的Spring Cloud Sleuth版本是2.x(对应Spring Boot 2.x),这些API是这个版本之后才稳定的。
  • propagation-keys只是控制哪些baggage要跨进程传播,本身不影响MDC同步,所以你还是需要通过上面的方式把baggage-keys里的内容同步到MDC。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:24:04