-
Notifications
You must be signed in to change notification settings - Fork 4
/
metrics.go
83 lines (78 loc) · 2.03 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
package main
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
func registerMetrics(pcs []*PatternConfig) error {
for idx, pc := range pcs {
log.WithFields(log.Fields{"metric": pc.Metric}).Info("Registering pattern")
err := pc.compile()
if err != nil {
return fmt.Errorf("pattern %d/%d[%s]: %s'", idx+1, len(pcs), pc.Metric, err)
}
switch pc.Type {
case "counter":
err := registerCounter(pc)
if err != nil {
return err
}
case "gauge":
err := registerGauge(pc)
if err != nil {
return err
}
default:
return fmt.Errorf("unknown type")
}
}
return nil
}
func registerCounter(pc *PatternConfig) error {
opts := prometheus.CounterOpts{
Name: pc.Metric,
Help: pc.Help,
}
labelNames := []string{}
for name := range pc.Labels {
labelNames = append(labelNames, name)
}
c := prometheus.NewCounterVec(opts, labelNames)
if len(pc.Labels) == 0 {
_ = c.WithLabelValues()
}
pc.CounterVec = c
err := prometheus.Register(pc.CounterVec)
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
// A counter for that metric has been registered before.
// Use the old counter from now on.
pc.CounterVec = are.ExistingCollector.(*prometheus.CounterVec)
log.Debug("counter already registered, using existing instance")
} else {
// Something else went wrong!
return err
}
return nil
}
func registerGauge(pc *PatternConfig) error {
opts := prometheus.GaugeOpts{
Name: pc.Metric,
Help: pc.Help,
}
labelNames := []string{}
for name := range pc.Labels {
labelNames = append(labelNames, name)
}
pc.GaugeVec = prometheus.NewGaugeVec(opts, labelNames)
err := prometheus.Register(pc.GaugeVec)
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
// A counter for that metric has been registered before.
// Use the old counter from now on.
pc.GaugeVec = are.ExistingCollector.(*prometheus.GaugeVec)
log.Debug("gauge already registered, using existing instance")
} else {
// Something else went wrong!
return err
}
return nil
}