-
Notifications
You must be signed in to change notification settings - Fork 3
/
tracer.go
86 lines (68 loc) · 2.1 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
82
83
84
85
86
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/attribute"
"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.23.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(name string) trace.Tracer {
return noop.NewTracerProvider().Tracer(name)
}
// NewTracer for tracer.
func NewTracer(ctx context.Context, lc fx.Lifecycle, name string, env env.Environment, ver version.Version, cfg *Config) (trace.Tracer, error) {
if cfg.Host == "" {
return NewNoopTracer(name), nil
}
opts := []otlptracehttp.Option{otlptracehttp.WithEndpoint(cfg.Host)}
if !cfg.Secure {
opts = append(opts, otlptracehttp.WithInsecure())
}
client := otlptracehttp.NewClient(opts...)
exporter, err := otlptrace.New(ctx, client)
if err != nil {
return nil, err
}
attrs := resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(name),
semconv.ServiceVersion(string(ver)),
semconv.DeploymentEnvironment(string(env)),
attribute.String("name", os.ExecutableName()),
)
tracerOpts := []sdktrace.TracerProviderOption{
sdktrace.WithResource(attrs),
}
if env.IsDevelopment() {
tracerOpts = append(tracerOpts, sdktrace.WithSyncer(exporter))
} else {
tracerOpts = append(tracerOpts, sdktrace.WithBatcher(exporter))
}
p := sdktrace.NewTracerProvider(tracerOpts...)
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) {
}