github.com/blend/go-sdk@v1.20220411.3/tracing/context.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package tracing
     9  
    10  import (
    11  	"context"
    12  	"strconv"
    13  
    14  	"github.com/blend/go-sdk/logger"
    15  
    16  	opentracing "github.com/opentracing/opentracing-go"
    17  )
    18  
    19  type tracerKey struct{}
    20  
    21  // WithTracer adds a tracer to a context.
    22  func WithTracer(ctx context.Context, tracer opentracing.Tracer) context.Context {
    23  	return context.WithValue(ctx, tracerKey{}, tracer)
    24  }
    25  
    26  // GetTracer gets a tracer from a context.
    27  func GetTracer(ctx context.Context) opentracing.Tracer {
    28  	if value := ctx.Value(tracerKey{}); value != nil {
    29  		if typed, ok := value.(opentracing.Tracer); ok {
    30  			return typed
    31  		}
    32  	}
    33  	return nil
    34  }
    35  
    36  // WithTraceAnnotations extracts trace span details as logger annotations onto a context
    37  func WithTraceAnnotations(ctx context.Context, span opentracing.SpanContext) context.Context {
    38  	if spanIDProvider, ok := span.(SpanIDProvider); ok {
    39  		ctx = logger.WithAnnotation(ctx, LoggerAnnotationTracingSpanID, strconv.FormatUint(spanIDProvider.SpanID(), 10))
    40  	}
    41  	if traceIDProvider, ok := span.(TraceIDProvider); ok {
    42  		ctx = logger.WithAnnotation(ctx, LoggerAnnotationTracingTraceID, strconv.FormatUint(traceIDProvider.TraceID(), 10))
    43  	}
    44  	return ctx
    45  }