-
Notifications
You must be signed in to change notification settings - Fork 18
/
metrics.go
114 lines (104 loc) · 2.46 KB
/
metrics.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
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
package otel
import (
"fmt"
"time"
"github.com/circleci/ex/o11y"
)
func extractAndSendMetrics(mp o11y.MetricsProvider) func([]o11y.Metric, map[string]interface{}) {
return func(metrics []o11y.Metric, fields map[string]interface{}) {
for _, m := range metrics {
tags := extractTagsFromFields(m.TagFields, fields)
switch m.Type {
case o11y.MetricTimer:
val, ok := getField(m.Field, fields)
if !ok {
continue
}
valFloat, ok := toMilliSecond(val)
if !ok {
panic(m.Field + " can not be coerced to milliseconds")
}
_ = mp.TimeInMilliseconds(m.Name, valFloat, tags, 1)
case o11y.MetricCount:
var valInt int64 = 1
if m.Field != "" {
val, ok := getField(m.Field, fields)
if !ok {
continue
}
valInt, ok = toInt64(val)
if !ok {
panic(m.Field + " can not be coerced to int")
}
}
if m.FixedTag != nil {
tags = append(tags, fmtTag(m.FixedTag.Name, m.FixedTag.Value))
}
_ = mp.Count(m.Name, valInt, tags, 1)
case o11y.MetricGauge:
val, ok := getField(m.Field, fields)
if !ok {
continue
}
valFloat, ok := toFloat64(val)
if !ok {
panic(m.Field + " can not be coerced to float")
}
_ = mp.Gauge(m.Name, valFloat, tags, 1)
}
}
}
}
func extractTagsFromFields(tags []string, fields map[string]interface{}) []string {
result := make([]string, 0, len(tags))
for _, name := range tags {
val, ok := getField(name, fields)
if ok {
result = append(result, fmtTag(name, val))
}
}
return result
}
func getField(name string, fields map[string]interface{}) (interface{}, bool) {
val, ok := fields[name]
if !ok {
// Also support the app. prefix, for interop with honeycomb's prefixed fields
val, ok = fields["app."+name]
}
return val, ok
}
func toInt64(val interface{}) (int64, bool) {
switch v := val.(type) {
case int64:
return v, true
case int:
return int64(v), true
}
return 0, false
}
func toFloat64(val interface{}) (float64, bool) {
if i, ok := val.(float64); ok {
return i, true
}
if i, ok := toInt64(val); ok {
return float64(i), true
}
return 0, false
}
func toMilliSecond(val interface{}) (float64, bool) {
if f, ok := toFloat64(val); ok {
return f, true
}
d, ok := val.(time.Duration)
if !ok {
p, ok := val.(*time.Duration)
if !ok {
return 0, false
}
d = *p
}
return float64(d.Milliseconds()), true
}
func fmtTag(name string, val interface{}) string {
return fmt.Sprintf("%s:%v", name, val)
}