2020-12-08 00:38:37 +03:00
|
|
|
// Package tracer provides an interface for distributed tracing
|
2020-10-16 09:38:57 +03:00
|
|
|
package tracer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
2021-03-04 01:12:16 +03:00
|
|
|
type tracerKey struct{}
|
2020-10-16 09:38:57 +03:00
|
|
|
|
2021-03-04 01:12:16 +03:00
|
|
|
// FromContext returns a tracer from context
|
2021-10-07 22:46:47 +03:00
|
|
|
func FromContext(ctx context.Context) (Tracer, bool) {
|
2021-03-04 01:12:16 +03:00
|
|
|
if ctx == nil {
|
2021-10-07 22:46:47 +03:00
|
|
|
return nil, false
|
2021-03-04 01:12:16 +03:00
|
|
|
}
|
|
|
|
if tracer, ok := ctx.Value(tracerKey{}).(Tracer); ok {
|
2021-10-07 22:46:47 +03:00
|
|
|
return tracer, true
|
2020-12-17 22:52:00 +03:00
|
|
|
}
|
2021-10-07 22:46:47 +03:00
|
|
|
return nil, false
|
2021-03-04 01:12:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewContext saves the tracer in the context
|
|
|
|
func NewContext(ctx context.Context, tracer Tracer) context.Context {
|
|
|
|
if ctx == nil {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
|
|
|
return context.WithValue(ctx, tracerKey{}, tracer)
|
|
|
|
}
|
|
|
|
|
|
|
|
type spanKey struct{}
|
|
|
|
|
|
|
|
// SpanFromContext returns a span from context
|
2021-10-07 22:46:47 +03:00
|
|
|
func SpanFromContext(ctx context.Context) (Span, bool) {
|
2021-03-04 01:12:16 +03:00
|
|
|
if ctx == nil {
|
2021-10-07 22:46:47 +03:00
|
|
|
return nil, false
|
2020-10-16 09:38:57 +03:00
|
|
|
}
|
2021-03-04 01:12:16 +03:00
|
|
|
if span, ok := ctx.Value(spanKey{}).(Span); ok {
|
2021-10-07 22:46:47 +03:00
|
|
|
return span, true
|
2020-10-16 09:38:57 +03:00
|
|
|
}
|
2021-10-07 22:46:47 +03:00
|
|
|
return nil, false
|
2020-10-16 09:38:57 +03:00
|
|
|
}
|
|
|
|
|
2021-03-04 01:12:16 +03:00
|
|
|
// NewSpanContext saves the span in the context
|
|
|
|
func NewSpanContext(ctx context.Context, span Span) context.Context {
|
|
|
|
if ctx == nil {
|
|
|
|
ctx = context.Background()
|
2020-12-17 22:52:00 +03:00
|
|
|
}
|
2021-03-04 01:12:16 +03:00
|
|
|
return context.WithValue(ctx, spanKey{}, span)
|
2020-10-16 09:38:57 +03:00
|
|
|
}
|