go-micro.dev/v5@v5.12.0/debug/trace/trace.go (about)

     1  // Package trace provides an interface for distributed tracing
     2  package trace
     3  
     4  import (
     5  	"context"
     6  	"time"
     7  
     8  	"go-micro.dev/v5/metadata"
     9  	"go-micro.dev/v5/transport/headers"
    10  )
    11  
    12  var (
    13  	// DefaultTracer is the default tracer.
    14  	DefaultTracer = NewTracer()
    15  )
    16  
    17  // Tracer is an interface for distributed tracing.
    18  type Tracer interface {
    19  	// Start a trace
    20  	Start(ctx context.Context, name string) (context.Context, *Span)
    21  	// Finish the trace
    22  	Finish(*Span) error
    23  	// Read the traces
    24  	Read(...ReadOption) ([]*Span, error)
    25  }
    26  
    27  // SpanType describe the nature of the trace span.
    28  type SpanType int
    29  
    30  const (
    31  	// SpanTypeRequestInbound is a span created when serving a request.
    32  	SpanTypeRequestInbound SpanType = iota
    33  	// SpanTypeRequestOutbound is a span created when making a service call.
    34  	SpanTypeRequestOutbound
    35  )
    36  
    37  // Span is used to record an entry.
    38  type Span struct {
    39  	// Start time
    40  	Started time.Time
    41  	// associated data
    42  	Metadata map[string]string
    43  	// Id of the trace
    44  	Trace string
    45  	// name of the span
    46  	Name string
    47  	// id of the span
    48  	Id string
    49  	// parent span id
    50  	Parent string
    51  	// Duration in nano seconds
    52  	Duration time.Duration
    53  	// Type
    54  	Type SpanType
    55  }
    56  
    57  // FromContext returns a span from context.
    58  func FromContext(ctx context.Context) (traceID string, parentSpanID string, isFound bool) {
    59  	traceID, traceOk := metadata.Get(ctx, headers.TraceIDKey)
    60  	microID, microOk := metadata.Get(ctx, headers.ID)
    61  
    62  	if !traceOk && !microOk {
    63  		isFound = false
    64  		return
    65  	}
    66  
    67  	if !traceOk {
    68  		traceID = microID
    69  	}
    70  
    71  	parentSpanID, ok := metadata.Get(ctx, headers.SpanID)
    72  
    73  	return traceID, parentSpanID, ok
    74  }
    75  
    76  // ToContext saves the trace and span ids in the context.
    77  func ToContext(ctx context.Context, traceID, parentSpanID string) context.Context {
    78  	return metadata.MergeContext(ctx, map[string]string{
    79  		headers.TraceIDKey: traceID,
    80  		headers.SpanID:     parentSpanID,
    81  	}, true)
    82  }