-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric.go
107 lines (88 loc) · 2.23 KB
/
metric.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
package redis
import (
"context"
"fmt"
"strings"
"time"
"github.com/go-redis/redis/v8"
"github.com/prometheus/client_golang/prometheus"
)
type (
Metric struct {
addr []string
master string
db int
}
)
const (
start = "start"
)
var (
cmdTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "redis_client_command_total",
Help: "redis command counter",
},
[]string{"address", "db", "masterName", "pipe", "cmd", "error"},
)
cmdElapsedSummary = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "redis_client_command_duration_seconds",
Help: "redis command duration seconds",
Objectives: map[float64]float64{
0.25: 0.05,
0.5: 0.05,
0.75: 0.05,
0.9: 0.01,
0.99: 0.001,
},
},
[]string{"address", "db", "masterName", "pipe", "cmd", "error"},
)
)
func init() {
prometheus.MustRegister(cmdElapsedSummary, cmdTotal)
}
func (m *Metric) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
return context.WithValue(ctx, start, time.Now()), nil
}
func (m *Metric) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
start := ctx.Value(start).(time.Time)
elapsed := time.Since(start)
m.report(false, elapsed, cmd)
return nil
}
func (m *Metric) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
return context.WithValue(ctx, start, time.Now()), nil
}
func (m *Metric) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
start := ctx.Value(start).(time.Time)
elapsed := time.Since(start)
m.report(true, elapsed, cmds...)
return nil
}
func (m *Metric) report(pipe bool, elapsed time.Duration, cmds ...redis.Cmder) {
addressStr := strings.Join(m.addr, ",")
dbStr := fmt.Sprintf("%d", m.db)
masterNameStr := m.master
errStr := ""
cmdStr := ""
pipeStr := fmt.Sprintf("%t", pipe)
for _, cmd := range cmds {
cmdStr += cmd.Name() + ";"
if err := cmd.Err(); err != nil && err != redis.Nil {
errStr += err.Error() + ";"
}
}
cmdStr = strings.TrimSuffix(cmdStr, ";")
values := []string{
addressStr,
dbStr,
masterNameStr,
pipeStr,
cmdStr,
errStr,
}
cmdElapsedSummary.WithLabelValues(values...).Observe(elapsed.Seconds())
cmdTotal.WithLabelValues(values...).Inc()
}