/
metrics.go
123 lines (108 loc) · 2.38 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"errors"
"expvar"
)
const (
//DatabaseOK is databse state if everything is OK.
DatabaseOK = "OK"
//DatabaseNotConnected is database
//state if some errors in connection occurs
DatabaseNotConnected = "NOT CONNECTED"
)
var (
//ErrMetricsNotInitialized occurs if
//metrics are not analyzed
ErrMetricsNotInitialized = errors.New("Metrics not initialized")
)
//MetricFunc is function
//executed if metrics are initi
type metricsFunc func()
//Metrics struct
//provides interface to
//hold metrics
type Metrics struct {
initialized bool
comparison *expvar.Int
errors *expvar.Int
database *expvar.String
}
//NewMetrics creates
//Metrics object
func NewMetrics() *Metrics {
metrics = &Metrics{
true,
expvar.NewInt("comparisons"),
expvar.NewInt("errors"),
expvar.NewString("database"),
}
return metrics
}
//AddComparison increments
//the number of comparisons in
//metrics object by given value
func (m *Metrics) AddComparison(value int64) error {
return m.doIfNotNil(func() {
m.comparison.Add(value)
})
}
//AddError increments the
//value of errors
func (m *Metrics) AddError(value int64) error {
return m.doIfNotNil(func() {
m.errors.Add(value)
})
}
//ComparisonInc increments the
//value of comparisons
//in matrics object by 1
func (m *Metrics) ComparisonInc() error {
return m.doIfNotNil(func() {
m.comparison.Add(1)
})
}
//ErrorInc increments the value
//of error in metrics struc by 1
func (m *Metrics) ErrorInc() error {
return m.doIfNotNil(func() {
m.errors.Add(1)
})
}
//SetDatabaseState sets the state of database
//for displaying in health check
func (m *Metrics) SetDatabaseState(state string) error {
return m.doIfNotNil(func() {
m.database.Set(state)
})
}
//GetDatabaseState retrieves the state of database
//for displaying in health check
func (m *Metrics) GetDatabaseState() string {
if m.errors != nil {
return m.database.String()
}
return ""
}
//GetErrors returns the number of
//errors
func (m *Metrics) GetErrors() string {
if m.errors != nil {
return m.errors.String()
}
return ""
}
//GetComparisons returns the string value
//of comparison count
func (m *Metrics) GetComparisons() string {
if m.comparison != nil {
return m.comparison.String()
}
return ""
}
func (m *Metrics) doIfNotNil(function metricsFunc) error {
if m != nil && m.initialized {
function()
return nil
}
return ErrMetricsNotInitialized
}