-
Notifications
You must be signed in to change notification settings - Fork 3
/
otel.go
93 lines (78 loc) · 2.24 KB
/
otel.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
87
88
89
90
91
92
93
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/topi314/tint"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/exporters/prometheus"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/semconv/v1.25.0"
"go.opentelemetry.io/otel/trace"
"github.com/topi314/gobin/v2/server"
)
func resources(cfg server.OtelConfig) *resource.Resource {
return resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(Name),
semconv.ServiceNamespace(Namespace),
semconv.ServiceInstanceID(cfg.InstanceID),
semconv.ServiceVersion(Version),
)
}
func newTracer(cfg server.OtelConfig) (trace.Tracer, error) {
if cfg.Trace == nil {
return nil, nil
}
opts := []otlptracehttp.Option{
otlptracehttp.WithEndpoint(cfg.Trace.Endpoint),
}
if cfg.Trace.Insecure {
opts = append(opts, otlptracehttp.WithInsecure())
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
exp, err := otlptracehttp.New(ctx, opts...)
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(resources(cfg)),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
return otel.Tracer(Name), nil
}
func newMeter(cfg server.OtelConfig) (metric.Meter, error) {
if cfg.Metrics == nil {
return nil, nil
}
exp, err := prometheus.New()
if err != nil {
return nil, err
}
mp := sdkmetric.NewMeterProvider(
sdkmetric.WithReader(exp),
sdkmetric.WithResource(resources(cfg)),
)
otel.SetMeterProvider(mp)
httpServer := &http.Server{
Addr: cfg.Metrics.ListenAddr,
Handler: promhttp.Handler(),
}
go func() {
if listenErr := httpServer.ListenAndServe(); listenErr != nil && !errors.Is(listenErr, http.ErrServerClosed) {
slog.Error("failed to listen metrics server", tint.Err(listenErr))
}
}()
return mp.Meter(Name), nil
}