-
Notifications
You must be signed in to change notification settings - Fork 0
/
attribute.go
65 lines (60 loc) · 1.73 KB
/
attribute.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
package otelzap
import (
"encoding/json"
"fmt"
"reflect"
"go.opentelemetry.io/otel/attribute"
)
func Attribute(key string, value interface{}) attribute.KeyValue {
switch value := value.(type) {
case nil:
return attribute.String(key, "<nil>")
case string:
return attribute.String(key, value)
case int:
return attribute.Int(key, value)
case int64:
return attribute.Int64(key, value)
case uint64:
return attribute.Int64(key, int64(value))
case float64:
return attribute.Float64(key, value)
case bool:
return attribute.Bool(key, value)
case fmt.Stringer:
return attribute.String(key, value.String())
}
rv := reflect.ValueOf(value)
switch rv.Kind() {
case reflect.Array:
rv = rv.Slice(0, rv.Len())
fallthrough
case reflect.Slice:
switch reflect.TypeOf(value).Elem().Kind() {
case reflect.Bool:
return attribute.BoolSlice(key, rv.Interface().([]bool))
case reflect.Int:
return attribute.IntSlice(key, rv.Interface().([]int))
case reflect.Int64:
return attribute.Int64Slice(key, rv.Interface().([]int64))
case reflect.Float64:
return attribute.Float64Slice(key, rv.Interface().([]float64))
case reflect.String:
return attribute.StringSlice(key, rv.Interface().([]string))
default:
return attribute.KeyValue{Key: attribute.Key(key)}
}
case reflect.Bool:
return attribute.Bool(key, rv.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return attribute.Int64(key, rv.Int())
case reflect.Float64:
return attribute.Float64(key, rv.Float())
case reflect.String:
return attribute.String(key, rv.String())
}
if b, err := json.Marshal(value); b != nil && err == nil {
return attribute.String(key, string(b))
}
return attribute.String(key, fmt.Sprint(value))
}