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

Spring Boot 3中基于OpenTelemetry定义Baggage并关联MDC的实现

Spring Boot 3 + OpenTelemetry 实现自定义Baggage并关联MDC

1. 替换依赖(build.gradle)

把原有的Brave桥接依赖换成OpenTelemetry版本,适配Spring Boot 3的依赖如下:

...
implementation 'io.micrometer:context-propagation:1.0.5'
implementation 'io.micrometer:micrometer-tracing'
// 替换Brave桥为OpenTelemetry桥
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
// 按需添加OpenTelemetry SDK或导出器依赖
implementation 'io.opentelemetry:opentelemetry-sdk'
implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
...

2. 配置文件调整(application.yml)

OpenTelemetry的Baggage配置逻辑和Brave基本一致,但需额外启用Baggage传播器:

management:
  endpoints:
    web:
      exposure:
        include: "health,info"
  tracing:
    sampling:
      probability: 1.0
    baggage:
      correlation:
        fields:
          - myBaggage  # 指定要关联到MDC的字段
      remote-fields:
        - myBaggage  # 指定跨服务传播的字段
opentelemetry:
  propagators: baggage,tracecontext  # 必须包含baggage才能跨服务传播自定义字段

3. 自定义Baggage与MDC关联的配置类

OpenTelemetry没有Brave那样的MDCScopeDecorator,需要通过监听上下文变化来同步Baggage到MDC,或者直接在设置Baggage时手动同步:

import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.context.Context;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Consumer;

@Configuration
public class LoggingContextConfig {

    public static final String MY_BAGGAGE_KEY = "myBaggage";

    // 配置上下文变化时自动同步Baggage到MDC
    @Bean
    Consumer<Context> mdcBaggageSyncer() {
        return context -> {
            Baggage baggage = Baggage.fromContext(context);
            String baggageValue = baggage.getEntryValue(MY_BAGGAGE_KEY);
            if (baggageValue != null) {
                MDC.put(MY_BAGGAGE_KEY, baggageValue);
            } else {
                MDC.remove(MY_BAGGAGE_KEY);
            }
        };
    }

    // 封装设置Baggage的工具方法,方便业务代码调用
    public static void setMyBaggage(String value) {
        Baggage updatedBaggage = Baggage.current().toBuilder()
                .put(MY_BAGGAGE_KEY, value)
                .build();
        // 将Baggage绑定到当前上下文
        updatedBaggage.makeCurrent();
        // 手动同步到MDC(确保日志实时生效)
        MDC.put(MY_BAGGAGE_KEY, value);
        // Spring Web环境下,上下文Scope会在请求结束时自动关闭,无需手动处理
    }
}

关键差异说明

  • API层面:Brave的BaggageField被替换为OpenTelemetry的Baggage API,创建和管理Baggage的方式更偏向于上下文构建模式
  • MDC关联:不再依赖Brave的MDCScopeDecorator,而是通过自定义上下文消费者实现自动同步,也可以在设置Baggage时手动同步
  • 传播控制:必须显式配置opentelemetry.propagators包含baggage,否则自定义字段无法跨服务传播

业务代码中使用示例

在需要设置自定义Baggage的地方调用工具方法即可,后续日志会自动包含该字段:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class BusinessService {
    private static final Logger log = LoggerFactory.getLogger(BusinessService.class);

    public void execute() {
        // 设置自定义Baggage
        LoggingContextConfig.setMyBaggage("user_1001");
        // 日志中会自动带上myBaggage=user_1001
        log.info("执行核心业务逻辑");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:43:28