...
1 package metrics
2
3 import (
4 "time"
5
6 "github.com/prometheus/client_golang/prometheus"
7 )
8
9
10
11 func StartTimer(timer Timer) (done func()) {
12 start := time.Now()
13 return func() {
14 timer.Update(time.Since(start))
15 }
16 }
17
18
19 type Timer interface {
20
21
22 Update(duration time.Duration)
23
24
25
26 UpdateSince(time.Time)
27 }
28
29
30 type LabeledTimer interface {
31 WithValues(labels ...string) *labeledTimerObserver
32 }
33
34 type labeledTimer struct {
35 m *prometheus.HistogramVec
36 }
37
38 type labeledTimerObserver struct {
39 m prometheus.Observer
40 }
41
42 func (lbo *labeledTimerObserver) Update(duration time.Duration) {
43 lbo.m.Observe(duration.Seconds())
44 }
45
46 func (lbo *labeledTimerObserver) UpdateSince(since time.Time) {
47 lbo.m.Observe(time.Since(since).Seconds())
48 }
49
50 func (lt *labeledTimer) WithValues(labels ...string) *labeledTimerObserver {
51 return &labeledTimerObserver{m: lt.m.WithLabelValues(labels...)}
52 }
53
54 func (lt *labeledTimer) Describe(c chan<- *prometheus.Desc) {
55 lt.m.Describe(c)
56 }
57
58 func (lt *labeledTimer) Collect(c chan<- prometheus.Metric) {
59 lt.m.Collect(c)
60 }
61
62 type timer struct {
63 m prometheus.Observer
64 }
65
66 func (t *timer) Update(duration time.Duration) {
67 t.m.Observe(duration.Seconds())
68 }
69
70 func (t *timer) UpdateSince(since time.Time) {
71 t.m.Observe(time.Since(since).Seconds())
72 }
73
74 func (t *timer) Describe(c chan<- *prometheus.Desc) {
75 c <- t.m.(prometheus.Metric).Desc()
76 }
77
78 func (t *timer) Collect(c chan<- prometheus.Metric) {
79
80
81
82
83
84 t.m.(prometheus.Collector).Collect(c)
85 }
86
View as plain text