0

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

Praveen Kumar K S
  • 3,024
  • 1
  • 24
  • 31
HughWPHamill
  • 58
  • 10
  • Any chance for a small sample to replicate the issue? – Marcin Grzejszczak May 29 '18 at 16:21
  • Hi @MarcinGrzejszczak I've added some sample code and project above, thanks! – HughWPHamill May 31 '18 at 11:03
  • Have you read the documentation of sleuth? We specifically describe how to retrieve the tracing context. You should use the second way via the tracer. – Marcin Grzejszczak May 31 '18 at 11:38
  • Thanks, if you want to put that in an answer I'll accept the answer. I looked at http://cloud.spring.io/spring-cloud-static/spring-cloud-sleuth/1.3.3.RELEASE/single/spring-cloud-sleuth.html Ctrl+F for currentSpan().context().traceIdString() shows no hits though and it wasn't immediately obvious how to extract the trace id. even traceIdString() shows only two hits and it's in some sample code for the section on Spring Integration. – HughWPHamill May 31 '18 at 11:52
  • Ok then can you file an issue so that we update the docs? – Marcin Grzejszczak May 31 '18 at 12:05
  • 1
    Sure, will do, thanks again. – HughWPHamill May 31 '18 at 12:43

1 Answers1

1

In the documentation we've described how to access the tracing context. To get the trace id via the tracer interface.

Marcin Grzejszczak
  • 10,624
  • 1
  • 16
  • 32