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

如何基于Spring Boot与Micrometer实现按端点的链路追踪?

问题描述

我有一个暴露两个端点的REST API:

  • 端点1(/businessCriticalFLow)流量低但属于核心业务,需要追踪从控制器层到仓储层的全链路;
  • 端点2(/notSoImportant)流量极高,但可观测性要求低,无需链路追踪。

现有代码示例:

@RestController
class ReportController {

  private static final Logger LOGGER = LoggerFactory.getLogger(ReportController.class);

  @Autowired
  ReportService reportService;

  @GetMapping("/businessCriticalFLow")
  String businessCriticalFLow(@RequestBody String string) {
    LOGGER.info("would like to see traces like this INFO [app,bbe3aea006077640b66d40f3e62f04b9,93b7a150b7e293ef]");
    Report report = reportService.getReport(string); // 会追踪到仓储层的调用链路
    return ...;
  }

  @GetMapping("/notSoImportant")
  String notSoImportant(@RequestParam(value = "id", required = true) int id) {
      return ...;
  }

}

当前尝试的三种解决方案均存在问题:

  • 完全禁用追踪:丢失端点1的可观测性;
  • 全局启用追踪:因端点2的无用追踪浪费成本;
  • 拆分为两个应用:实施成本较高。

请问是否可通过Spring Boot与Micrometer实现按流、按端点的链路追踪?


解决方案

可以实现,通过Micrometer Tracing的自定义采样策略,就能精准控制哪些端点开启全链路追踪,具体步骤如下:

1. 引入必要依赖

确保Spring Boot项目中包含Micrometer Tracing相关依赖(以Maven为例):

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2. 自定义采样器

通过实现Sampler接口,基于请求路径判断是否开启追踪:

import io.micrometer.tracing.Sampler;
import io.micrometer.tracing.TraceContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Configuration
public class TracingConfig {

    @Bean
    public Sampler endpointBasedSampler() {
        return new Sampler() {
            @Override
            public boolean isSampled(TraceContext traceContext) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    // 仅对核心业务端点开启采样追踪
                    return "/businessCriticalFLow".equals(request.getRequestURI());
                }
                // 默认不追踪
                return false;
            }
        };
    }
}

3. 配置日志链路输出

确保日志框架(如Logback)集成MDC,自动在日志中携带Trace ID和Span ID,示例Logback配置片段:

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg [%X{traceId},%X{spanId}]%n</pattern>
    </encoder>
</appender>

效果验证

配置完成后:

  • 访问/businessCriticalFLow时,会生成完整的链路追踪数据,从控制器到Service、Repository的所有调用都会被记录,日志中也会显示对应的Trace ID和Span ID;
  • 访问/notSoImportant时,不会生成任何追踪数据,避免了不必要的资源消耗。

注意:若使用Spring Boot 3.x,Micrometer Tracing的API细节略有差异,但核心逻辑一致,都是通过自定义采样器实现基于请求路径的追踪控制。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:05:17