redis_hook.go 1015 Bytes
Newer Older
hujiebin's avatar
hujiebin committed
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
package redisCli

import (
	"context"
	"git.hilo.cn/hilo-common/mylogrus"
	"github.com/go-redis/redis/v8"
	"time"
)

type redisCost struct{}

var redisCostKey = redisCost{}

type redisHook struct{}

func (redisHook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
	ctx = context.WithValue(ctx, redisCostKey, time.Now())
	return ctx, nil
}

func (redisHook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
	traceId, userId := ctx.Value("traceId"), ctx.Value("userId")
	start := ctx.Value(redisCostKey)
	var cost int64
	if s, ok := start.(time.Time); ok {
		cost = time.Now().Sub(s).Milliseconds()
	}
28
	mylogrus.RedisLog.Infof("redis cmd: <%s>,err:%v traceId:%v,userId:%v,cost:%v ms", cmd.String(), cmd.Err(), traceId, userId, cost)
hujiebin's avatar
hujiebin committed
29 30 31 32 33 34 35 36 37 38
	return nil
}

func (redisHook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
	return ctx, nil
}

func (redisHook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
	return nil
}