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
|
package solomon
import (
"encoding/json"
"time"
"github.com/ydb-platform/ydb/library/go/core/metrics"
"go.uber.org/atomic"
)
var (
_ metrics.Counter = (*Counter)(nil)
_ Metric = (*Counter)(nil)
)
// Counter tracks monotonically increasing value.
type Counter struct {
name string
metricType metricType
tags map[string]string
value atomic.Int64
timestamp *time.Time
useNameTag bool
}
// Inc increments counter by 1.
func (c *Counter) Inc() {
c.Add(1)
}
// Add adds delta to the counter. Delta must be >=0.
func (c *Counter) Add(delta int64) {
c.value.Add(delta)
}
func (c *Counter) Name() string {
return c.name
}
func (c *Counter) getType() metricType {
return c.metricType
}
func (c *Counter) getLabels() map[string]string {
return c.tags
}
func (c *Counter) getValue() interface{} {
return c.value.Load()
}
func (c *Counter) getTimestamp() *time.Time {
return c.timestamp
}
func (c *Counter) getNameTag() string {
if c.useNameTag {
return "name"
} else {
return "sensor"
}
}
// MarshalJSON implements json.Marshaler.
func (c *Counter) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
Labels map[string]string `json:"labels"`
Value int64 `json:"value"`
Timestamp *int64 `json:"ts,omitempty"`
}{
Type: c.metricType.String(),
Value: c.value.Load(),
Labels: func() map[string]string {
labels := make(map[string]string, len(c.tags)+1)
labels[c.getNameTag()] = c.Name()
for k, v := range c.tags {
labels[k] = v
}
return labels
}(),
Timestamp: tsAsRef(c.timestamp),
})
}
// Snapshot returns independent copy on metric.
func (c *Counter) Snapshot() Metric {
return &Counter{
name: c.name,
metricType: c.metricType,
tags: c.tags,
value: *atomic.NewInt64(c.value.Load()),
useNameTag: c.useNameTag,
}
}
|