如何为Sleuth Span添加控制器方法名及自定义信息?
自定义Spring Cloud Sleuth的Span名称与添加额外信息
一、自定义Span名称(显示Controller方法名)
方法1:使用@SpanName注解
直接在Controller方法上标注@SpanName,指定想要显示的名称(可以是方法名或自定义名称):
import org.springframework.cloud.sleuth.annotation.SpanName; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @SpanName("getUserDetail") @GetMapping("/user/{id}") public String getUserDetail(String id) { // 业务逻辑实现 return "user-info-" + id; } }
配置后,Span名称会直接显示为getUserDetail。
方法2:自定义SpanNameProvider实现自动命名
如果希望自动以类名.方法名作为Span名称,无需手动加注解,可以实现SpanNameProvider接口:
import org.springframework.cloud.sleuth.SpanNameProvider; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; @Component public class MethodBasedSpanNameProvider implements SpanNameProvider { @Override public String getName(MethodParameter methodParameter) { return methodParameter.getContainingClass().getSimpleName() + "." + methodParameter.getMethod().getName(); } }
所有被Sleuth追踪的Controller方法会自动使用类名.方法名作为Span名称,比如UserController.getUserDetail。
二、添加额外自定义追踪信息(Tags)
方式1:使用@NewSpan + @Tag注解
通过注解快速给Span添加固定或参数关联的Tag:
import org.springframework.cloud.sleuth.annotation.NewSpan; import org.springframework.cloud.sleuth.annotation.Tag; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @NewSpan(name = "getUserDetail") @Tag(key = "user_id", expression = "#id") @Tag(key = "request_source", expression = "'api'") @GetMapping("/user/{id}") public String getUserDetail(@PathVariable String id) { // 业务逻辑实现 return "user-info-" + id; } }
这里会给Span添加两个Tag:user_id(值为请求的id参数)、request_source(固定值api)。
方式2:通过Tracer手动添加动态Tag
如果需要在业务逻辑中动态添加Tag,直接注入Tracer操作当前Span:
import org.springframework.cloud.sleuth.Tracer; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource private Tracer tracer; @GetMapping("/user/{id}") public String getUserDetail(@PathVariable String id) { // 动态添加自定义Tag tracer.currentSpan().tag("user_id", id); tracer.currentSpan().tag("business_scene", "user_query"); tracer.currentSpan().tag("result_code", "success"); // 业务逻辑实现 return "user-info-" + id; } }
这种方式支持在代码任意位置添加自定义信息,适合需要根据业务逻辑动态生成Tag的场景。
三、可选:全局配置调整
可以通过application.yml配置全局Span命名规则:
spring: sleuth: web: span-name-regex: "^[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$" # 限制Span名称的格式
内容的提问来源于stack exchange,提问作者Dmitry Shabalin
相关产品推荐
相关产品推荐

