Reputation: 58
I have a @ControllerAdvice
which is returning VndError
from spring-hateoas. VndError
specifies a logRef
field which is where I should be putting the Trace ID from Spring Cloud Sleuth. Is there an official way to do this, or should I just retrieve it from the MDC directly in my @ControllerAdvice
@ExceptionHandler
method?
Example Controller Advice:
@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 Example: https://github.com/hughwphamill/spring-traceid-logref
Upvotes: 0
Views: 1614
Reputation: 11189
In the documentation we've described how to access the tracing context. To get the trace id via the tracer interface.
Upvotes: 1