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
|
package solomon
import (
"encoding/json"
"time"
"github.com/ydb-platform/ydb/library/go/core/metrics"
"go.uber.org/atomic"
)
var (
_ metrics.Timer = (*Timer)(nil)
_ Metric = (*Timer)(nil)
)
// Timer measures gauge duration.
type Timer struct {
name string
metricType metricType
tags map[string]string
value atomic.Duration
timestamp *time.Time
useNameTag bool
}
func (t *Timer) RecordDuration(value time.Duration) {
t.value.Store(value)
}
func (t *Timer) Name() string {
return t.name
}
func (t *Timer) getType() metricType {
return t.metricType
}
func (t *Timer) getLabels() map[string]string {
return t.tags
}
func (t *Timer) getValue() interface{} {
return t.value.Load().Seconds()
}
func (t *Timer) getTimestamp() *time.Time {
return t.timestamp
}
func (t *Timer) getNameTag() string {
if t.useNameTag {
return "name"
} else {
return "sensor"
}
}
// MarshalJSON implements json.Marshaler.
func (t *Timer) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
Labels map[string]string `json:"labels"`
Value float64 `json:"value"`
Timestamp *int64 `json:"ts,omitempty"`
}{
Type: t.metricType.String(),
Value: t.value.Load().Seconds(),
Labels: func() map[string]string {
labels := make(map[string]string, len(t.tags)+1)
labels[t.getNameTag()] = t.Name()
for k, v := range t.tags {
labels[k] = v
}
return labels
}(),
Timestamp: tsAsRef(t.timestamp),
})
}
// Snapshot returns independent copy on metric.
func (t *Timer) Snapshot() Metric {
return &Timer{
name: t.name,
metricType: t.metricType,
tags: t.tags,
value: *atomic.NewDuration(t.value.Load()),
useNameTag: t.useNameTag,
}
}
|