tiny-rdm/backend/utils/redis/log_hook.go

49 lines
1.0 KiB
Go
Raw Normal View History

2023-06-27 15:53:29 +08:00
package redis
import (
"context"
"github.com/redis/go-redis/v9"
"log"
"net"
)
2023-07-16 01:50:01 +08:00
type execCallback func(string)
2023-06-27 15:53:29 +08:00
type LogHook struct {
2023-07-16 01:50:01 +08:00
name string
cmdExec execCallback
2023-06-27 15:53:29 +08:00
}
2023-07-16 01:50:01 +08:00
func NewHook(name string, cmdExec execCallback) *LogHook {
return &LogHook{
name: name,
cmdExec: cmdExec,
2023-06-27 15:53:29 +08:00
}
}
2023-07-16 01:50:01 +08:00
func (l *LogHook) DialHook(next redis.DialHook) redis.DialHook {
2023-06-27 15:53:29 +08:00
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return next(ctx, network, addr)
}
}
2023-07-16 01:50:01 +08:00
func (l *LogHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
2023-06-27 15:53:29 +08:00
return func(ctx context.Context, cmd redis.Cmder) error {
2023-07-16 01:50:01 +08:00
log.Println(cmd)
if l.cmdExec != nil {
l.cmdExec(cmd.String())
}
2023-06-27 15:53:29 +08:00
return next(ctx, cmd)
}
}
2023-07-16 01:50:01 +08:00
func (l *LogHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
2023-06-27 15:53:29 +08:00
return func(ctx context.Context, cmds []redis.Cmder) error {
for _, cmd := range cmds {
2023-07-16 01:50:01 +08:00
log.Println("pipeline: ", cmd)
if l.cmdExec != nil {
l.cmdExec(cmd.String())
}
2023-06-27 15:53:29 +08:00
}
return next(ctx, cmds)
}
}