首页 > 解决方案 > 如何将 Spring Cloud Sleuth Trace ID 填充到 spring-hateoas 中 VndError 的 logRef 字段中?

问题描述

我有一个从 spring-hateoas @ControllerAdvice返回的。指定一个字段,我应该在其中放置来自 Spring Cloud Sleuth 的 Trace ID。有没有官方的方法可以做到这一点,还是我应该直接在我的方法中从 MDC 中检索它?VndErrorVndErrorlogRef@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

标签: springspring-bootspring-hateoasspring-cloud-sleuth

解决方案


在文档中,我们描述了如何访问跟踪上下文。通过 tracer 接口获取 trace id。


推荐阅读