/
tracer.go
78 lines (62 loc) · 1.94 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
package tracer
import (
"context"
"runtime"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"github.com/batazor/shortlink/internal/pkg/logger/field"
)
func NewTraceFromContext(
ctx context.Context,
msg string,
tags []attribute.KeyValue,
fields ...field.Fields,
) ([]field.Fields, error) { // nolint:contextcheck,maintidx
if ctx == nil {
ctx = context.Background()
}
_, span := otel.Tracer("logger").Start(ctx, getNameFunc())
defer span.End()
span.SetAttributes(ZapFieldsToOpenTelemetry(fields...)...)
span.SetAttributes(attribute.String("log", msg))
span.SetAttributes(tags...)
// Get span ID
if len(fields) == 0 {
fields = make([]field.Fields, 0)
}
fields = append(fields, field.Fields{ // nozero
"traceID": span.SpanContext().TraceID().String(),
})
return fields, nil
}
func getNameFunc() string {
// at least 1 entry needed
pc := make([]uintptr, 10) // nolint:gomnd
runtime.Callers(4, pc) // nolint:gomnd
f := runtime.FuncForPC(pc[0])
return f.Name()
}
// ZapFieldsToOpenTelemetry returns a table of standard openTelemetry field based on
// the inputed table of Zap field.
func ZapFieldsToOpenTelemetry(fields ...field.Fields) []attribute.KeyValue {
openTelemetryFields := make([]attribute.KeyValue, 0, len(fields))
for key := range fields {
for k := range fields[key] {
switch v := fields[key][k].(type) {
case string:
openTelemetryFields = append(openTelemetryFields, attribute.String(k, v))
case bool:
openTelemetryFields = append(openTelemetryFields, attribute.Bool(k, v))
case int:
openTelemetryFields = append(openTelemetryFields, attribute.Int(k, v))
case int32:
openTelemetryFields = append(openTelemetryFields, attribute.Int(k, int(v)))
case int64:
openTelemetryFields = append(openTelemetryFields, attribute.Int64(k, v))
case error:
openTelemetryFields = append(openTelemetryFields, attribute.String(k, v.Error()))
}
}
}
return openTelemetryFields
}