-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathtracing.go
79 lines (66 loc) · 2.44 KB
/
tracing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package tracing
import (
"context"
"io"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
jaeger "github.com/uber/jaeger-client-go"
jaegercfg "github.com/uber/jaeger-client-go/config"
jaegerprom "github.com/uber/jaeger-lib/metrics/prometheus"
)
// ErrInvalidConfiguration is an error to notify client to provide valid trace report agent or config server
var (
ErrBlankTraceConfiguration = errors.New("no trace report agent, config server, or collector endpoint specified")
)
// installJaeger registers Jaeger as the OpenTracing implementation.
func installJaeger(serviceName string, cfg *jaegercfg.Configuration, options ...jaegercfg.Option) (io.Closer, error) {
metricsFactory := jaegerprom.New()
// put the metricsFactory earlier so provided options can override it
opts := append([]jaegercfg.Option{jaegercfg.Metrics(metricsFactory)}, options...)
closer, err := cfg.InitGlobalTracer(serviceName, opts...)
if err != nil {
return nil, errors.Wrap(err, "could not initialize jaeger tracer")
}
return closer, nil
}
// NewFromEnv is a convenience function to allow tracing configuration
// via environment variables
//
// Tracing will be enabled if one (or more) of the following environment variables is used to configure trace reporting:
// - JAEGER_AGENT_HOST
// - JAEGER_SAMPLER_MANAGER_HOST_PORT
func NewFromEnv(serviceName string, options ...jaegercfg.Option) (io.Closer, error) {
cfg, err := jaegercfg.FromEnv()
if err != nil {
return nil, errors.Wrap(err, "could not load jaeger tracer configuration")
}
if cfg.Sampler.SamplingServerURL == "" && cfg.Reporter.LocalAgentHostPort == "" && cfg.Reporter.CollectorEndpoint == "" {
return nil, ErrBlankTraceConfiguration
}
return installJaeger(serviceName, cfg, options...)
}
// ExtractTraceID extracts the trace id, if any from the context.
func ExtractTraceID(ctx context.Context) (string, bool) {
sp := opentracing.SpanFromContext(ctx)
if sp == nil {
return "", false
}
sctx, ok := sp.Context().(jaeger.SpanContext)
if !ok {
return "", false
}
return sctx.TraceID().String(), true
}
// ExtractSampledTraceID works like ExtractTraceID but the returned bool is only
// true if the returned trace id is sampled.
func ExtractSampledTraceID(ctx context.Context) (string, bool) {
sp := opentracing.SpanFromContext(ctx)
if sp == nil {
return "", false
}
sctx, ok := sp.Context().(jaeger.SpanContext)
if !ok {
return "", false
}
return sctx.TraceID().String(), sctx.IsSampled()
}