1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-01-05 10:20:53 +02:00
go-micro/debug/trace/trace.go

83 lines
1.8 KiB
Go
Raw Normal View History

2020-01-18 12:20:46 +02:00
// Package trace provides an interface for distributed tracing
package trace
import (
"context"
"time"
2024-06-04 22:40:43 +02:00
"go-micro.dev/v5/metadata"
"go-micro.dev/v5/transport/headers"
)
var (
// DefaultTracer is the default tracer.
DefaultTracer = NewTracer()
2020-01-18 12:20:46 +02:00
)
2022-09-30 16:27:07 +02:00
// Tracer is an interface for distributed tracing.
2020-01-29 17:45:11 +02:00
type Tracer interface {
2020-01-18 12:20:46 +02:00
// Start a trace
2020-01-24 23:44:48 +02:00
Start(ctx context.Context, name string) (context.Context, *Span)
2020-01-18 12:20:46 +02:00
// Finish the trace
Finish(*Span) error
// Read the traces
Read(...ReadOption) ([]*Span, error)
}
2022-09-30 16:27:07 +02:00
// SpanType describe the nature of the trace span.
type SpanType int
const (
2022-09-30 16:27:07 +02:00
// SpanTypeRequestInbound is a span created when serving a request.
SpanTypeRequestInbound SpanType = iota
2022-09-30 16:27:07 +02:00
// SpanTypeRequestOutbound is a span created when making a service call.
SpanTypeRequestOutbound
)
2022-09-30 16:27:07 +02:00
// Span is used to record an entry.
2020-01-18 12:20:46 +02:00
type Span struct {
2023-04-26 02:16:34 +02:00
// Start time
Started time.Time
// associated data
Metadata map[string]string
2020-01-18 12:20:46 +02:00
// Id of the trace
Trace string
// name of the span
Name string
// id of the span
Id string
// parent span id
Parent string
2020-01-24 23:24:51 +02:00
// Duration in nano seconds
Duration time.Duration
// Type
Type SpanType
2020-01-18 12:20:46 +02:00
}
2022-09-30 16:27:07 +02:00
// FromContext returns a span from context.
func FromContext(ctx context.Context) (traceID string, parentSpanID string, isFound bool) {
traceID, traceOk := metadata.Get(ctx, headers.TraceIDKey)
microID, microOk := metadata.Get(ctx, headers.ID)
if !traceOk && !microOk {
isFound = false
return
}
if !traceOk {
traceID = microID
}
parentSpanID, ok := metadata.Get(ctx, headers.SpanID)
return traceID, parentSpanID, ok
2020-01-18 12:20:46 +02:00
}
2022-09-30 16:27:07 +02:00
// ToContext saves the trace and span ids in the context.
func ToContext(ctx context.Context, traceID, parentSpanID string) context.Context {
return metadata.MergeContext(ctx, map[string]string{
headers.TraceIDKey: traceID,
headers.SpanID: parentSpanID,
}, true)
2020-01-18 12:20:46 +02:00
}