spring - 如何将 Spring Cloud Sleuth Trace ID 填充到 spring-hateoas 中 VndError 的 logRef 字段中?
问题描述
我有一个从 spring-hateoas @ControllerAdvice
返回的。指定一个字段,我应该在其中放置来自 Spring Cloud Sleuth 的 Trace ID。有没有官方的方法可以做到这一点,还是我应该直接在我的方法中从 MDC 中检索它?VndError
VndError
logRef
@ControllerAdvice
@ExceptionHandler
示例控制器建议:
@ControllerAdvice
class ExceptionHandler {
@Autowired
private lateinit var tracer: Tracer
@ExceptionHandler(LocalException::class)
fun handleLocalException(e: LocalException): ResponseEntity<VndErrors.VndError> {
val traceId = MDC.get("X-B3-TraceId") // <-- Is this the correct way of getting trace id from Sleuth?
val traceId2 = tracer.currentSpan().context().traceIdString() // <-- Or something like this?
val error = VndErrors.VndError(traceId, e.message)
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error)
}
}
GitHub 示例: https ://github.com/hughwphamill/spring-traceid-logref
解决方案
在文档中,我们描述了如何访问跟踪上下文。通过 tracer 接口获取 trace id。
推荐阅读
- reactjs - 我的减速器不断覆盖该值
- java - Grails Groovy 配置 Log4j
- gitlab - 在 gitlab runner 上共享 docker 容器内的卷
- javascript - 为什么我的画布在将 html 转换为 DOM 调用时会自行缩放?
- javascript - 我怎样才能让我的按钮来选择我的工具来绘制不同的形状?
- mysql - SQL 中“>ALL”VS“MAX()”的性能
- python-3.x - tkinter 计算器中的小数
- django - 在 django 中从前端向数据库添加数据
- java - 使用 Datanucleus 的 Amazon S3 数据存储
- spring - 如何通过 spring AbstractMongoEventListener 检测 mongo 数据库更改