Package brave.baggage

Class CorrelationScopeDecorator

  • All Implemented Interfaces:
    CurrentTraceContext.ScopeDecorator

    public abstract class CorrelationScopeDecorator
    extends Object
    implements CurrentTraceContext.ScopeDecorator
    Synchronizes fields such as BaggageFields.TRACE_ID with a correlation context, such as logging through decoration of a scope. A maximum of 32 fields are supported.

    Setup example:

    
     import brave.baggage.CorrelationScopeConfig.SingleCorrelationField;
    
     // Add the field "region", so it can be used as a log expression %X{region}
     CLOUD_REGION = BaggageFields.constant("region", System.getEnv("CLOUD_REGION"));
    
     decorator = MDCScopeDecorator.newBuilder()
                                  .add(SingleCorrelationField.create(CLOUD_REGION))
                                  .build();
    
     // Integrate the decorator
     tracing = Tracing.newBuilder()
                      .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
                        .addScopeDecorator(decorator)
                        .build())
                      ...
                      .build();
    
     // Any scope operations (updates to the current span) apply the fields defined by the decorator.
     ScopedSpan span = tracing.tracer().startScopedSpan("encode");
     try {
       // The below log message will have %X{region} in the context!
       logger.info("Encoding the span, hope it works");
       return encoder.encode();
     } catch (RuntimeException | Error e) {
       span.error(e); // Unless you handle exceptions, you might not know the operation failed!
       throw e;
     } finally {
       span.finish();
     }
     
    Since:
    5.11
    See Also:
    CorrelationScopeConfig, CorrelationScopeCustomizer, BaggagePropagation