spring cloud 默认的日志追踪工具是什么

Spring Cloud默认的日志追踪工具是Spring Cloud Sleuth。Spring Cloud Sleuth 为Spring Boot应用程序中的分布式追踪提供了支持,通过自动生成并传播追踪信息,帮助开发者跟踪请求在微服务架构中的传播路径。

Spring Cloud Sleuth 的主要功能

  1. 自动生成追踪ID和跨度ID

    • 每个请求都会自动生成一个唯一的追踪ID(Trace ID)和跨度ID(Span ID),这些ID会在请求链条中传递,用于标识和跟踪请求。
  2. 整合日志系统

    • Sleuth 会在日志中自动添加追踪信息,包括Trace ID和Span ID,这样在日志中可以轻松地关联不同服务间的请求。
  3. 传播追踪信息

    • Sleuth 会自动将追踪信息添加到HTTP请求、消息队列等通信方式中,确保在整个分布式系统中都能跟踪到请求的传播路径。
  4. 与Zipkin集成

    • Sleuth 可以与Zipkin集成,将追踪数据发送到Zipkin进行集中存储和分析。

集成Spring Cloud Sleuth

依赖配置

在Spring Boot项目的pom.xml文件中添加Spring Cloud Sleuth的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>
</dependencies>

如果需要将追踪数据发送到Zipkin,还需要添加Zipkin的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zipkin</artifactId>
    </dependency>
</dependencies>

配置文件

application.propertiesapplication.yml中进行必要的配置:

# 配置Zipkin服务器地址
spring.zipkin.base-url=http://localhost:9411
# 配置采样率,1.0表示100%采样
spring.sleuth.sampler.probability=1.0

示例代码

一个简单的Spring Boot应用程序使用Spring Cloud Sleuth进行分布式追踪:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class SleuthDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SleuthDemoApplication.class, args);
    }
}

@RestController
class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Sleuth!";
    }
}

日志输出

在运行上述应用程序并访问http://localhost:8080/hello时,你会在日志中看到类似如下的信息:

2023-06-09 12:34:56.789  INFO [sleuth-demo,9f1c2e3d2b1e1e3f,9f1c2e3d2b1e1e3f,false] 1 --- [nio-8080-exec-1] c.e.demo.HelloController                 : Hello, Sleuth!

这里的[sleuth-demo,9f1c2e3d2b1e1e3f,9f1c2e3d2b1e1e3f,false]部分即为Sleuth添加的追踪信息,包含应用名、Trace ID、Span ID等。

总结

Spring Cloud Sleuth 是Spring Cloud生态系统中的默认日志追踪工具,通过自动生成和传播追踪信息,帮助开发者跟踪和分析分布式系统中的请求路径。它与日志系统的无缝集成,使得在复杂的微服务架构中也能轻松进行日志关联和问题排查。

posted @   gongchengship  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示