forked from seedco/go-lob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.go
54 lines (48 loc) · 1.1 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
package lob
import (
"time"
"github.com/rcrowley/go-metrics"
)
// MetricsBundle is a bundle of a timer and two meters,
// for success and failure. It is useful for, e.g.,
// API endpoints.
type MetricsBundle struct {
Timer metrics.Timer
Success metrics.Meter
Error metrics.Meter
}
// NewMetricsBundle creates a new metrics bundle and
// registers them with the given name as a prefix.
func NewMetricsBundle(name string) *MetricsBundle {
m := &MetricsBundle{
Timer: metrics.NewTimer(),
Success: metrics.NewMeter(),
Error: metrics.NewMeter(),
}
err := metrics.Register(name+".timer", m.Timer)
if err != nil {
panic(err)
}
metrics.Register(name+".success", m.Success)
if err != nil {
panic(err)
}
metrics.Register(name+".error", m.Error)
if err != nil {
panic(err)
}
return m
}
// Call calls a function returning an error, and passes
// it back, while recording timing and success information.
func (m *MetricsBundle) Call(f func() error) error {
ts := time.Now()
defer m.Timer.UpdateSince(ts)
err := f()
if err != nil {
m.Error.Mark(1)
} else {
m.Success.Mark(1)
}
return err
}