1. 【可观测性】Spring Boot 4 OpenTelemetry日志自动注入 TraceId1.1. 概述本文通过极简示例项目演示Spring Boot 4 接入 OpenTelemetry无需手动存储 TraceId、手动获取 TraceId即可在日志中自动带上分布式链路追踪 ID实现同一请求内日志串联。1.2. 背景与目标在微服务排查问题时最常用的手段就是通过traceId串联一次请求全链路日志。Spring Boot 4 内置的spring-boot-starter-opentelemetry开箱即用日志模板会自动带上 traceId、spanId。本示例目标同一个 HTTP 请求Controller、Service 日志的 traceId 保持一致不同 HTTP 请求traceId 自动生成不同值零自定义 存储和获取 TraceId 代码OpenTelemetry 依赖自动完成上下文传递。1.3. 环境信息Spring Boot4.1.2JDK21组件Spring Boot OpenTelemetry Starter、Spring Web MVC、Lombok1.4. 创建项目通过 Spring Initializr 创建项目项目名hello-opentelemetry-traceid1.5. 核心依赖引入 Spring Boot 官方封装的 OpenTelemetry Starter 。dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-opentelemetry/artifactId/dependency1.6. 业务代码编写1.6.1. HelloControllerpackagecom.example.hello_opentelemetry_traceid.hello;importlombok.RequiredArgsConstructor;importlombok.extern.slf4j.Slf4j;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;Slf4jRestControllerRequiredArgsConstructorpublicclassHelloController{privatefinalHelloServicehelloService;GetMapping(/hello)publicStringhello(){log.info(HelloController.hello());returnhelloService.hello();}}1.6.2. HelloServicepackagecom.example.hello_opentelemetry_traceid.hello;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Service;Slf4jServicepublicclassHelloService{publicStringhello(){log.info(HelloService.hello());returnHello World;}}✨ 重点代码里没有任何一行手动存储或获取 TraceId 的代码。1.7. 验证效果启动项目多次访问接口http://localhost:8080/hello1.7.1. 预期特征✅ 同一次请求Controller 和 Service 日志traceId完全相同✅ 不同请求自动生成全新traceId✅ traceId / spanId 自动输出在日志方括号内1.7.2. 日志样例2026-10-31T23:42:31.65308:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-1][f799ce83c38bd74f624968cccd5fa140-f0c2b359154d5137]c.e.h.hello.HelloController:HelloController.hello()2026-10-31T23:42:31.65408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-1][f799ce83c38bd74f624968cccd5fa140-f0c2b359154d5137]c.e.h.hello.HelloService:HelloService.hello()2026-10-31T23:42:46.97408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-2][a81820c0bfba4c9a8e9ebf3bbc97cf18-0840629a10e3ba3a]c.e.h.hello.HelloController:HelloController.hello()2026-10-31T23:42:46.97408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-2][a81820c0bfba4c9a8e9ebf3bbc97cf18-0840629a10e3ba3a]c.e.h.hello.HelloService:HelloService.hello()格式说明[traceId-spanId]前者是链路 ID后者是当前片段 ID。同一请求内Controller 与 Service 的 traceId 完全一致。两次不同请求的 traceId 则各不相同。至此可以确认OpenTelemetry 会自动将链路上下文注入日志的上下文存储中链路与日志的关联已经生效。2. 完整工程代码本章节为独立的完整代码汇总可直接复制搭建工程与上文分步讲解逻辑分离。2.1. POM?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion4.1.2/versionrelativePath//parentgroupIdcom.example/groupIdartifactIdhello-opentelemetry-traceid/artifactIdversion0.0.1-SNAPSHOT/versionpropertiesjava.version21/java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-opentelemetry/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webmvc/artifactId/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-opentelemetry-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webmvc-test/artifactIdscopetest/scope/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdexecutionsexecutioniddefault-compile/idphasecompile/phasegoalsgoalcompile/goal/goalsconfigurationannotationProcessorPathspathgroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/path/annotationProcessorPaths/configuration/executionexecutioniddefault-testCompile/idphasetest-compile/phasegoalsgoaltestCompile/goal/goalsconfigurationannotationProcessorPathspathgroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/path/annotationProcessorPaths/configuration/execution/executions/plugin/plugins/build/project2.2. application.ymlspring:application:name:hello-opentelemetry-traceid2.3. HelloOpentelemetryTraceidApplicationpackagecom.example.hello_opentelemetry_traceid;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplicationpublicclassHelloOpentelemetryTraceidApplication{publicstaticvoidmain(String[]args){SpringApplication.run(HelloOpentelemetryTraceidApplication.class,args);}}2.4. HelloControllerpackagecom.example.hello_opentelemetry_traceid.hello;importlombok.RequiredArgsConstructor;importlombok.extern.slf4j.Slf4j;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;Slf4jRestControllerRequiredArgsConstructorpublicclassHelloController{privatefinalHelloServicehelloService;GetMapping(/hello)publicStringhello(){log.info(HelloController.hello());returnhelloService.hello();}}2.5. HelloServicepackagecom.example.hello_opentelemetry_traceid.hello;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Service;Slf4jServicepublicclassHelloService{publicStringhello(){log.info(HelloService.hello());returnHello World;}}3. 附录完整启动日志.____ _ __ _ _ /\\/ ____ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | _|_| | _\/ _|\\\\\\/ ___)||_)|||||||(_||)))) |____| .__|_| |_|_| |_\__, | / / / / |_||___//_/_/_/ :: Spring Boot :: (v4.1.2) 2026-10-31T23:42:00.16108:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] e.h.HelloOpentelemetryTraceidApplication : Starting HelloOpentelemetryTraceidApplication using Java 21.0.1 with PID 10124 (E:\hello-world\hello-opentelemetry-traceid\target\classes started by SongGuanxun in E:\hello-world\hello-opentelemetry-traceid) 2026-10-31T23:42:00.17508:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] e.h.HelloOpentelemetryTraceidApplication : No active profile set, falling back to 1 default profile: default 2026-10-31T23:42:02.67308:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http) 2026-10-31T23:42:02.71108:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2026-10-31T23:42:02.71208:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/11.0.27] 2026-10-31T23:42:02.83408:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] b.w.c.s.WebApplicationContextInitializer : Root WebApplicationContext: initialization completed in 2471 ms 2026-10-31T23:42:03.53908:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] i.m.c.instrument.push.PushMeterRegistry : Publishing metrics for OtlpMeterRegistry every 1m to http://localhost:4318/v1/metrics with resource attributes {service.namehello-opentelemetry-traceid} 2026-10-31T23:42:04.43608:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path / 2026-10-31T23:42:04.44908:00 INFO 10124 --- [hello-opentelemetry-traceid] [ main] [ ] e.h.HelloOpentelemetryTraceidApplication : Started HelloOpentelemetryTraceidApplication in 5.798 seconds (process running for 7.846) 2026-10-31T23:42:31.47508:00 INFO 10124 --- [hello-opentelemetry-traceid] [nio-8080-exec-1] [ ] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet dispatcherServlet 2026-10-31T23:42:31.47608:00 INFO 10124 --- [hello-opentelemetry-traceid] [nio-8080-exec-1] [ ] o.s.web.servlet.DispatcherServlet : Initializing Servlet dispatcherServlet2026-10-31T23:42:31.47908:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-1][]o.s.web.servlet.DispatcherServlet:Completed initializationin3ms2026-10-31T23:42:31.65308:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-1][f799ce83c38bd74f624968cccd5fa140-f0c2b359154d5137]c.e.h.hello.HelloController:HelloController.hello()2026-10-31T23:42:31.65408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-1][f799ce83c38bd74f624968cccd5fa140-f0c2b359154d5137]c.e.h.hello.HelloService:HelloService.hello()2026-10-31T23:42:46.97408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-2][a81820c0bfba4c9a8e9ebf3bbc97cf18-0840629a10e3ba3a]c.e.h.hello.HelloController:HelloController.hello()2026-10-31T23:42:46.97408:00 INFO10124---[hello-opentelemetry-traceid][nio-8080-exec-2][a81820c0bfba4c9a8e9ebf3bbc97cf18-0840629a10e3ba3a]c.e.h.hello.HelloService:HelloService.hello()
阅读完成 · 觉得有帮助?