-
Notifications
You must be signed in to change notification settings - Fork 0
/
otel.go
77 lines (63 loc) · 1.6 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
package otel
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"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"
"runtime"
"strings"
)
var (
appName string
tracer trace.Tracer
)
type Options struct {
AppName string
JaegerURL string
TracerSampleRate float64
}
func init() {
tracer = otel.Tracer(appName)
}
func (o *Options) init() {
if o.AppName == "" {
o.AppName = "tracer-app"
}
if o.TracerSampleRate <= 0 {
o.TracerSampleRate = 1
}
appName = o.AppName
}
func NewTracer(opt *Options) (trace.TracerProvider, error) {
opt.init()
exporter, err := otlptracehttp.New(
context.Background(),
otlptracehttp.WithEndpointURL(opt.JaegerURL),
)
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithSampler(sdktrace.TraceIDRatioBased(opt.TracerSampleRate)),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(opt.AppName),
attribute.Int64("ID", 1),
)),
)
otel.SetTracerProvider(tp)
return tp, nil
}
func Tracer(ctx context.Context) (context.Context, trace.Span) {
pc, _, _, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(pc).Name()
funcNameSplit := strings.SplitN(funcName, ".", 2)
replacer := strings.NewReplacer("(", "", ")", "", "*", "")
operation := replacer.Replace(funcNameSplit[1])
return tracer.Start(ctx, operation)
}