Core

/app/lib/telemetry/span.go (2.4 KB)

  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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package telemetry

import (
"fmt"
"strings"

"github.com/samber/lo"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"go.opentelemetry.io/otel/trace"

"{{{ .Package }}}/app/util"
)

const disabledMsg = "[telemetry.disabled]"

type Span struct {
OT trace.Span
statusSet bool
}

func (s *Span) TraceID() string {
if s == nil || !Enabled {
return disabledMsg
}
return s.OT.SpanContext().TraceID().String()
}

func (s *Span) SpanID() string {
if s == nil || !Enabled {
return disabledMsg
}
return s.OT.SpanContext().SpanID().String()
}

func (s *Span) SetName(name string) {
if s == nil || !Enabled {
return
}
s.OT.SetName(name)
}

func (s *Span) SetStatus(status string, description string) {
if s == nil || !Enabled {
return
}
s.statusSet = true
switch strings.ToLower(status) {
case "ok":
s.OT.SetStatus(codes.Ok, description)
case util.KeyError:
s.OT.SetStatus(codes.Error, description)
default:
s.OT.SetStatus(codes.Ok, status+": "+description)
}
}

func (s *Span) Attribute(k string, v any) {
if s == nil || !Enabled {
return
}
s.Attributes(&Attribute{Key: k, Value: v})
}

func (s *Span) Attributes(attrs ...*Attribute) {
if s == nil || !Enabled {
return
}
ot := lo.Map(attrs, func(attr *Attribute, _ int) attribute.KeyValue {
return attr.ToOT()
})
s.OT.SetAttributes(ot...)
}

func (s *Span) Event(name string, attrs ...*Attribute) {
if s == nil || !Enabled {
return
}
s.OT.AddEvent(name)
lo.ForEach(attrs, func(attr *Attribute, _ int) {
s.OT.SetAttributes(attribute.KeyValue{
Key: attribute.Key(attr.Key),
Value: attribute.StringValue(fmt.Sprint(attr.Value)),
})
})
}

func (s *Span) OnError(err error) {
if s == nil || !Enabled {
return
}
s.OT.RecordError(err)
}

// Complete must be called, usually through a `defer` block.
func (s *Span) Complete() {
if s == nil || !Enabled {
return
}
if !s.statusSet {
s.SetStatus("ok", "complete")
}
s.OT.End()
}

func (s *Span) SetHTTPStatus(code int) {
if s == nil || !Enabled {
return
}
s.Attribute("http.status_code", code)
x, desc := semconv.SpanStatusFromHTTPStatusCode(code)
s.SetStatus(x.String(), desc)
}

func (s *Span) String() string {
if s == nil || !Enabled {
return disabledMsg
}
return s.SpanID() + "::" + s.TraceID()
}