redis_hook.go 1010 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 28 29 30 31 32 33 34 35 36 37 38
package redisCli

import (
	"context"
	"github.com/go-redis/redis/v8"
	"hilo-micCenter/common/mylogrus"
	"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()
	}
	mylogrus.MyLog.Infof("redis cmd: <%s>,err:%v traceId:%v,userId:%v,cost:%v ms", cmd.String(), cmd.Err(), traceId, userId, cost)
	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
}