如何使用 micrometer-brave 在 spring-cloud-gateway 中获取trace-id

2023-11-22

我想在 Spring Cloud Gateway 中的每个请求的日志中显示traceId。然而,traceId和spanId只是空的。

日志配置如下:

logging:
  pattern:
    level: "%5p [TRACE_ID: %X{traceId:-}] [SPAN_ID: %X{spanId:-}]"

pom.xml 的一部分:

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

使用 Spring Boot 3.x 和 Micrometer 1.10+,您可以尝试以下依赖项:

(pom.xml 的一部分)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-tracing-bridge-brave</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-observation</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <version>1.0.2</version>
        <artifactId>micrometer-tracing</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <version>1.0.2</version>
        <artifactId>context-propagation</artifactId>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.micrometer</groupId>
            <version>1.10.4</version>
            <artifactId>micrometer-bom</artifactId>
            <scope>import</scope>
        <type>pom</type>
    </dependency>
    </dependencies>
</dependencyManagement>

并在应用程序的主类中进行以下调用:

import reactor.core.publisher.Hooks;

public static void main(String[] args) {
    Hooks.enableAutomaticContextPropagation();
    // ...
}

Spring Boot 应该很快就会集成这些版本的依赖项并为您进行调用,但现在这些手动步骤应该会为您提供带有跟踪信息的日志。

在反应堆堆芯内3.5.3我们添加了注册的 ThreadLocal 值的自动传播上下文传播(可选)Micrometer 也使用的库。对于详细信息感兴趣的人,请查看PR介绍一下这个功能。这是对以下内容的总体增强3.5.0带来,其中 ThreadLocals 填充在特殊运算符中 ->handle and tap(及其重载)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 micrometer-brave 在 spring-cloud-gateway 中获取trace-id 的相关文章

随机推荐