-
Notifications
You must be signed in to change notification settings - Fork 9
/
metrics.go
94 lines (83 loc) · 1.64 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
94
package ecs
import "time"
type Metrics struct {
enable bool
isPrint bool
m map[string]*MetricReporter
}
func (m *Metrics) NewReporter(name string) *MetricReporter {
mr := &MetricReporter{
name: name,
sampleElapsed: []reporterStep{},
}
mr.metrics = m
return mr
}
func (m *Metrics) Print() {
if !m.enable {
return
}
for _, reporter := range m.m {
reporter.Print()
}
}
func NewMetrics(enable bool, print bool) *Metrics {
return &Metrics{
enable: enable,
isPrint: print,
m: make(map[string]*MetricReporter),
}
}
type reporterStep struct {
name string
elapsed time.Duration
}
type MetricReporter struct {
name string
metrics *Metrics
start time.Time
last time.Time
sampleElapsed []reporterStep
elapsedTotal time.Duration
}
func (m *MetricReporter) Start() {
if !m.metrics.enable {
return
}
m.start = time.Now()
m.last = m.start
}
func (m *MetricReporter) Sample(name string) {
if !m.metrics.enable {
return
}
now := time.Now()
m.elapsedTotal = now.Sub(m.start)
m.sampleElapsed = append(m.sampleElapsed, reporterStep{
name: name,
elapsed: now.Sub(m.last),
})
m.last = now
}
func (m *MetricReporter) Stop() {
if !m.metrics.enable {
return
}
now := time.Now()
m.elapsedTotal = now.Sub(m.start)
if m.metrics != nil {
m.metrics.m[m.name] = m
}
}
func (m *MetricReporter) Print(force ...bool) {
if !m.metrics.enable || !m.metrics.isPrint {
if len(force) > 0 && force[0] {
} else {
return
}
}
Log.Infof("%s: cost: %+v\n", m.name, m.elapsedTotal)
for _, r := range m.sampleElapsed {
Log.Infof(" ├─%20s: %+v\n", r.name, r.elapsed)
}
}