Handle tracing context with spring.cloud.sleuth - wk-tw/prez-tech-201106 GitHub Wiki

Distributed tracing

Trace Span System Workflow

Dependencies

implementation("org.springframework.cloud:spring-cloud-starter-sleuth")
implementation("org.springframework.cloud:spring-cloud-starter-zipkin")
dependencyManagement {
    imports {
        mavenBom("org.springframework.cloud:spring-cloud-dependencies:Hoxton.SR8")
    }
}

Tracing context

Tracer

@Bean Tracer from brave.Tracer

To get the context

tracer.currentSpan()?.context()

Default context

X─B3-TraceId, X─B3-ParentSpanId and X─B3-SpanId

tracer.currentSpan()?.context()?.traceId()
tracer.currentSpan()?.context()?.parentSpanId()
tracer.currentSpan()?.context()?.spanId()

B3 Propagation

Custom context

Add additional context attribute in application properties

spring:
  sleuth:
    baggage:
      remote-fields: x-trace-uuid       # To add custom additional field into tracing context
      correlation-fields: x-trace-uuid  # To add to correlation (MDC) context

Retrieve attribute in the application

From brave.baggage.BaggageField

BaggageField.getByName(X_TRACE_UUID).value

Logging

Without LogBack

Note: This will be overriden by logback-spring.xml

logging:
  pattern:
    level: "-%5p [${spring.application.name},%X{traceId},%X{spanId},%X{x-trace-uuid}]"

Logs Without LogBack

With LogBack

Retrieve correlated attribute x-trace-uuid

<property name="LOGGING_PATTERN_LEVEL" value="%highlight(%-5p) [%yellow(${appName}),%boldMagenta(%X{traceId}),%magenta(%X{spanId}),%green(%X{x-trace-uuid})]"/>

Custom Logging Pattern