hook.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package redis
  2. import (
  3. "context"
  4. "strings"
  5. "time"
  6. red "github.com/go-redis/redis/v8"
  7. "github.com/zeromicro/go-zero/core/logx"
  8. "github.com/zeromicro/go-zero/core/mapping"
  9. "github.com/zeromicro/go-zero/core/timex"
  10. )
  11. var (
  12. startTimeKey = contextKey("startTime")
  13. durationHook = hook{}
  14. )
  15. type (
  16. contextKey string
  17. hook struct{}
  18. )
  19. func (h hook) BeforeProcess(ctx context.Context, _ red.Cmder) (context.Context, error) {
  20. return context.WithValue(ctx, startTimeKey, timex.Now()), nil
  21. }
  22. func (h hook) AfterProcess(ctx context.Context, cmd red.Cmder) error {
  23. val := ctx.Value(startTimeKey)
  24. if val == nil {
  25. return nil
  26. }
  27. start, ok := val.(time.Duration)
  28. if !ok {
  29. return nil
  30. }
  31. duration := timex.Since(start)
  32. if duration > slowThreshold.Load() {
  33. logDuration(ctx, cmd, duration)
  34. }
  35. return nil
  36. }
  37. func (h hook) BeforeProcessPipeline(ctx context.Context, _ []red.Cmder) (context.Context, error) {
  38. return context.WithValue(ctx, startTimeKey, timex.Now()), nil
  39. }
  40. func (h hook) AfterProcessPipeline(ctx context.Context, cmds []red.Cmder) error {
  41. if len(cmds) == 0 {
  42. return nil
  43. }
  44. val := ctx.Value(startTimeKey)
  45. if val == nil {
  46. return nil
  47. }
  48. start, ok := val.(time.Duration)
  49. if !ok {
  50. return nil
  51. }
  52. duration := timex.Since(start)
  53. if duration > slowThreshold.Load()*time.Duration(len(cmds)) {
  54. logDuration(ctx, cmds[0], duration)
  55. }
  56. return nil
  57. }
  58. func logDuration(ctx context.Context, cmd red.Cmder, duration time.Duration) {
  59. var buf strings.Builder
  60. for i, arg := range cmd.Args() {
  61. if i > 0 {
  62. buf.WriteByte(' ')
  63. }
  64. buf.WriteString(mapping.Repr(arg))
  65. }
  66. logx.WithContext(ctx).WithDuration(duration).Slowf("[REDIS] slowcall on executing: %s", buf.String())
  67. }