-
Notifications
You must be signed in to change notification settings - Fork 3
/
tracer.go
81 lines (64 loc) · 2.12 KB
/
tracer.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
80
81
package tracer
import (
"context"
"github.com/alexfalkowski/go-service/env"
"github.com/alexfalkowski/go-service/os"
"github.com/alexfalkowski/go-service/version"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
"go.uber.org/fx"
)
// Register for tracer.
func Register() {
otel.SetTextMapPropagator(propagation.TraceContext{})
}
// NewNoopTracer for tracer.
func NewNoopTracer() trace.Tracer {
return noop.Tracer{}
}
// NewTracer for tracer.
func NewTracer(lc fx.Lifecycle, env env.Environment, ver version.Version, cfg *Config) (trace.Tracer, error) {
if !IsEnabled(cfg) {
return NewNoopTracer(), nil
}
opts := []otlptracehttp.Option{}
if cfg.IsBaselime() {
opts = append(opts, otlptracehttp.WithEndpointURL("https://otel.baselime.io"), otlptracehttp.WithHeaders(map[string]string{"x-api-key": cfg.Key}))
} else {
opts = append(opts, otlptracehttp.WithEndpointURL(cfg.Host))
}
return newTracer(context.Background(), lc, env, ver, opts)
}
func newTracer(ctx context.Context, lc fx.Lifecycle, env env.Environment, ver version.Version, opts []otlptracehttp.Option) (trace.Tracer, error) {
client := otlptracehttp.NewClient(opts...)
exporter, err := otlptrace.New(ctx, client)
if err != nil {
return nil, err
}
name := os.ExecutableName()
attrs := resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(name),
semconv.ServiceVersion(string(ver)),
semconv.DeploymentEnvironment(string(env)),
)
p := sdktrace.NewTracerProvider(sdktrace.WithResource(attrs), sdktrace.WithBatcher(exporter))
otel.SetTracerProvider(p)
otel.SetErrorHandler(&errorHandler{})
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
return p.Shutdown(ctx)
},
})
return p.Tracer(name), nil
}
type errorHandler struct{}
func (*errorHandler) Handle(_ error) {
}