-
Notifications
You must be signed in to change notification settings - Fork 0
/
slowlog.go
80 lines (61 loc) · 2.06 KB
/
slowlog.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
package longredis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
)
var startTimeKey = "_longredis_start_time"
var clientidKey = "_longredis_client_id"
type slowlog struct {
slowTime time.Duration
logLevel LogLevel
}
func (h *slowlog) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
return context.WithValue(ctx, startTimeKey, time.Now()), nil
}
func (h *slowlog) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
it := ctx.Value(startTimeKey)
t := it.(time.Time)
d := time.Now().Sub(t)
if d > h.slowTime { // 超时
SlowCounter.Inc()
Log(h.logLevel, "longredis slowlog", "duration", d.String(), "baseline", h.slowTime.String(), "command", cmd.FullName())
}
return nil
}
func (h *slowlog) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
return context.WithValue(ctx, startTimeKey, time.Now()), nil
}
func (h *slowlog) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
it := ctx.Value(startTimeKey)
t := it.(time.Time)
d := time.Now().Sub(t)
if d > h.slowTime { // 超时
SlowCounter.Inc()
cmdStr := ""
for _, cmd := range cmds {
cmdStr += cmd.FullName() + "; "
}
Log(h.logLevel, "longredis slowlog", "duration", d.String(), "baseline", h.slowTime.String(), "cmdcounts", len(cmds), "command", cmdStr)
}
return nil
}
type injectorHook struct {
clientid string
}
func (h *injectorHook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
ctx = context.WithValue(ctx, startTimeKey, time.Now())
ctx = context.WithValue(ctx, clientidKey, h.clientid)
return ctx, nil
}
func (h *injectorHook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
return nil
}
func (h *injectorHook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
ctx = context.WithValue(ctx, startTimeKey, time.Now())
ctx = context.WithValue(ctx, clientidKey, h.clientid)
return ctx, nil
}
func (h *injectorHook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
return nil
}