Allow setting tracer in the context. (#672)

Allows people to avoid setting a global if they don't want to.
This commit is contained in:
Brian Goff
2019-06-19 23:33:16 -07:00
committed by Pires
parent b9920e7cc4
commit f6be3ce713

View File

@@ -38,9 +38,25 @@ var (
T Tracer = nopTracer{}
)
type tracerKey struct{}
// WithTracer sets the Tracer which will be used by `StartSpan` in the context.
func WithTracer(ctx context.Context, t Tracer) context.Context {
return context.WithValue(ctx, tracerKey{}, t)
}
// StartSpan starts a span from the configured default tracer
func StartSpan(ctx context.Context, name string) (context.Context, Span) {
ctx, span := T.StartSpan(ctx, name)
t := ctx.Value(tracerKey{})
var tracer Tracer
if t != nil {
tracer = t.(Tracer)
} else {
tracer = T
}
ctx, span := tracer.StartSpan(ctx, name)
ctx = log.WithLogger(ctx, span.Logger())
return ctx, span
}