-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemit.go
88 lines (74 loc) · 2.09 KB
/
emit.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
package metrics
import (
"errors"
"strings"
"time"
"github.com/armon/go-metrics"
)
type valueType interface {
int32 | float32 | time.Duration
}
type metricType[V valueType] int
const (
count metricType[int32] = 1
gauge metricType[float32] = 2
distribution metricType[float32] = 3
timing metricType[time.Duration] = 4
)
type metricOptions struct {
tags []string
}
func (mo metricOptions) Labels() []metrics.Label {
labels := make([]metrics.Label, len(mo.tags))
for i, tag := range mo.tags {
parts := strings.Split(tag, ":")
labels[i] = metrics.Label{Name: parts[0]}
if len(parts) > 1 {
labels[i].Value = parts[1]
}
}
return labels
}
type metricOption func(*metricOptions)
// WithTags applies a set of tags to the metric being emitted. These are
// appended to the [Client]'s persistent tags (see [WithPersistentTags]). Tags
// should be strings of the form key:value.
func WithTags(tags ...string) metricOption {
return func(mo *metricOptions) {
mo.tags = append(mo.tags, tags...)
}
}
func (c Client) applyOptions(opts ...metricOption) metricOptions {
mo := metricOptions{tags: c.tags}
for _, opt := range opts {
opt(&mo)
}
return mo
}
// Emit emits a value for the provided metric [Identifier] using the provided
// [Client].
//
// Options include:
// - [WithTags]
func Emit[V valueType](client Client, metric Identifier[V], val V, opts ...metricOption) error {
switch int(metric.mt) {
case 1:
return client.count(metric.name, int64(val), opts...)
case 2:
return client.gauge(metric.name, float32(val), opts...)
case 3:
return client.distribution(metric.name, float32(val), opts...)
case 4:
return client.timing(metric.name, time.Duration(val), opts...)
default:
return errors.New("invalid metric identifier")
}
}
// GlobalEmit emits a value for the provided metric [Identifier] using the
// [Client] configured for the package globally, see [GlobalConfig].
//
// Options include:
// - [WithTags]
func GlobalEmit[V valueType](metric Identifier[V], val V, opts ...metricOption) error {
return Emit(global, metric, val, opts...)
}