forked from SpectoLabs/hoverfly
/
metrics.go
93 lines (77 loc) · 2.5 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
84
85
86
87
88
89
90
91
92
93
package hoverfly
import (
log "github.com/Sirupsen/logrus"
"github.com/rcrowley/go-metrics"
"time"
)
// CounterByMode - container for mode counters, registry and flush interval
type CounterByMode struct {
counterVirtualize, counterCapture, counterModify, counterSynthesize metrics.Counter
registry metrics.Registry
flushInterval time.Duration
}
// NewModeCounter - returns new counter instance
func NewModeCounter() *CounterByMode {
registry := metrics.NewRegistry()
c := &CounterByMode{
counterVirtualize: metrics.NewCounter(),
counterCapture: metrics.NewCounter(),
counterModify: metrics.NewCounter(),
counterSynthesize: metrics.NewCounter(),
registry: registry,
flushInterval: 5 * time.Second,
}
c.registry.GetOrRegister(VirtualizeMode, c.counterVirtualize)
c.registry.GetOrRegister(CaptureMode, c.counterCapture)
c.registry.GetOrRegister(ModifyMode, c.counterModify)
c.registry.GetOrRegister(SynthesizeMode, c.counterSynthesize)
log.Debug("new counter created, registration successful")
return c
}
// Count - counts requests based on mode
func (c *CounterByMode) Count(mode string) {
if mode == VirtualizeMode {
c.counterVirtualize.Inc(1)
} else if mode == CaptureMode {
c.counterCapture.Inc(1)
} else if mode == ModifyMode {
c.counterModify.Inc(1)
} else if mode == SynthesizeMode {
c.counterSynthesize.Inc(1)
}
}
// Init initializes logging
func (c *CounterByMode) Init() {
go func() {
for _ = range time.Tick(c.flushInterval) {
m := c.Flush()
log.WithFields(log.Fields{"counters": m.Counters}).Info("hoverfly metrics")
}
}()
}
// Stats - holds information about various system metrics like requests counts
type Stats struct {
Counters map[string]int64 `json:"counters"`
Gauges map[string]int64 `json:"gauges,omitempty"`
GaugesFloat map[string]float64 `json:"gaugesFloat,omitempty"`
}
// Flush gets current metrics from stats registry
func (c *CounterByMode) Flush() (h Stats) {
counters := make(map[string]int64)
gauges := make(map[string]int64)
gaugesFloat := make(map[string]float64)
c.registry.Each(func(name string, i interface{}) {
switch metric := i.(type) {
case metrics.Counter:
counters[name] = metric.Count()
case metrics.Gauge:
gauges[name] = metric.Value()
case metrics.GaugeFloat64:
gaugesFloat[name] = metric.Value()
}
})
h.Counters = counters
h.Gauges = gauges
h.GaugesFloat = gaugesFloat
return
}