-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspan.go
72 lines (58 loc) · 1.92 KB
/
span.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
package oteltag
import (
"reflect"
"strings"
"go.opentelemetry.io/otel/attribute"
"github.com/remychantenay/otel-tag/internal"
)
// SpanAttributes takes in a struct and spits out OpenTelemetry span attributes ([attribute.KeyValue])
// based on the struct tags.
func SpanAttributes(res any) []attribute.KeyValue {
return structToAttributes(res)
}
// structToAttributes returns a slice of [attribute.KeyValue] for a struct.
func structToAttributes(s any) []attribute.KeyValue {
structValue := reflect.ValueOf(s)
structType := structValue.Type()
fieldCount := structValue.NumField()
if fieldCount == 0 {
return nil
}
attrs := make([]attribute.KeyValue, 0, fieldCount)
for i := 0; i < fieldCount; i++ {
field, fieldValue := structType.Field(i), structValue.Field(i)
if field.Type.Kind() == reflect.Struct && fieldValue.IsValid() {
attrs = append(attrs, structToAttributes(fieldValue.Interface())...)
} else if field.Type.Kind() == reflect.Pointer && fieldValue.IsValid() { // Known shortcoming, assuming a pointer can only be a struct.
attrs = append(attrs, structToAttributes(fieldValue.Elem().Interface())...)
} else {
attr := basicTypeToAttribute(structType, structValue, i)
if !attr.Valid() {
continue
}
attrs = append(attrs, attr)
}
}
return attrs
}
// basicTypeToAttribute returns an [attribute.KeyValue] for a basic type.
func basicTypeToAttribute(structType reflect.Type, structValue reflect.Value, index int) attribute.KeyValue {
tag := internal.ExtractTag(structValue, index)
if tag == "" {
return attribute.KeyValue{}
}
var omitEmpty bool
before, after, found := strings.Cut(tag, ",")
if found {
tag = before
if after == flagOmitEmpty {
omitEmpty = true
}
}
field, fieldValue := structType.Field(index), structValue.Field(index)
attr, zeroValue := internal.SpanAttribute(field, fieldValue, tag)
if zeroValue && omitEmpty {
return attribute.KeyValue{}
}
return attr
}