This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
counter.go
80 lines (65 loc) · 2.4 KB
/
counter.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
package labeled
import (
"context"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/flyteorg/flytestdlib/contextutils"
"github.com/flyteorg/flytestdlib/promutils"
"github.com/prometheus/client_golang/prometheus"
)
// Counter represents a counter labeled with values from the context. See labeled.SetMetricsKeys for information about to
// configure that.
type Counter struct {
*prometheus.CounterVec
prometheus.Counter
labels []contextutils.Key
}
// Inc increments the counter by 1. Use Add to increment it by arbitrary non-negative values. The data point will be
// labeled with values from context. See labeled.SetMetricsKeys for information about how to configure that.
func (c Counter) Inc(ctx context.Context) {
counter, err := c.CounterVec.GetMetricWith(contextutils.Values(ctx, c.labels...))
if err != nil {
panic(err.Error())
}
counter.Inc()
if c.Counter != nil {
c.Counter.Inc()
}
}
// Add adds the given value to the counter. It panics if the value is < 0.. The data point will be labeled with values
// from context. See labeled.SetMetricsKeys for information about how to configure that.
func (c Counter) Add(ctx context.Context, v float64) {
counter, err := c.CounterVec.GetMetricWith(contextutils.Values(ctx, c.labels...))
if err != nil {
panic(err.Error())
}
counter.Add(v)
if c.Counter != nil {
c.Counter.Add(v)
}
}
// NewCounter creates a new labeled counter. Label keys must be set before instantiating a counter. See labeled.SetMetricsKeys for
// information about to configure that.
func NewCounter(name, description string, scope promutils.Scope, opts ...MetricOption) Counter {
if len(metricKeys) == 0 {
panic(ErrNeverSet)
}
c := Counter{}
name = promutils.SanitizeMetricName(name)
for _, opt := range opts {
if _, emitUnlabeledMetric := opt.(EmitUnlabeledMetricOption); emitUnlabeledMetric {
c.Counter = scope.MustNewCounter(GetUnlabeledMetricName(name), description)
} else if additionalLabels, casted := opt.(AdditionalLabelsOption); casted {
// compute unique labels
labelSet := sets.NewString(metricStringKeys...)
labelSet.Insert(additionalLabels.Labels...)
labels := labelSet.List()
c.CounterVec = scope.MustNewCounterVec(name, description, labels...)
c.labels = contextutils.MetricKeysFromStrings(labels)
}
}
if c.CounterVec == nil {
c.CounterVec = scope.MustNewCounterVec(name, description, metricStringKeys...)
c.labels = metricKeys
}
return c
}