Tracing: traces now correctly form a tree (#1170)
* First cut of trace * Dial it back yo * Defensive programming
This commit is contained in:
@@ -3,6 +3,7 @@ package trace
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/micro/go-micro/v2/metadata"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -34,17 +35,32 @@ type Span struct {
|
||||
Metadata map[string]string
|
||||
}
|
||||
|
||||
type spanKey struct{}
|
||||
const (
|
||||
traceIDKey = "Micro-Trace-Id"
|
||||
spanIDKey = "Micro-Span-Id"
|
||||
)
|
||||
|
||||
// FromContext returns a span from context
|
||||
func FromContext(ctx context.Context) (*Span, bool) {
|
||||
s, ok := ctx.Value(spanKey{}).(*Span)
|
||||
return s, ok
|
||||
func FromContext(ctx context.Context) (traceID string, parentSpanID string, isFound bool) {
|
||||
traceID, traceOk := metadata.Get(ctx, traceIDKey)
|
||||
microID, microOk := metadata.Get(ctx, "Micro-Id")
|
||||
if !traceOk && !microOk {
|
||||
isFound = false
|
||||
return
|
||||
}
|
||||
if !traceOk {
|
||||
traceID = microID
|
||||
}
|
||||
parentSpanID, ok := metadata.Get(ctx, spanIDKey)
|
||||
return traceID, parentSpanID, ok
|
||||
}
|
||||
|
||||
// NewContext creates a new context with the span
|
||||
func NewContext(ctx context.Context, s *Span) context.Context {
|
||||
return context.WithValue(ctx, spanKey{}, s)
|
||||
// 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{
|
||||
traceIDKey: traceID,
|
||||
spanIDKey: parentSpanID,
|
||||
}, true)
|
||||
}
|
||||
|
||||
var (
|
||||
|
Reference in New Issue
Block a user