hook.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. "github.com/zeromicro/go-zero/core/trace"
  11. "go.opentelemetry.io/otel"
  12. tracestd "go.opentelemetry.io/otel/trace"
  13. )
  14. var (
  15. startTimeKey = contextKey("startTime")
  16. spanKey = contextKey("span")
  17. durationHook = hook{tracer: otel.GetTracerProvider().Tracer(trace.TraceName)}
  18. )
  19. type (
  20. contextKey string
  21. hook struct {
  22. tracer tracestd.Tracer
  23. }
  24. )
  25. func (h hook) BeforeProcess(ctx context.Context, _ red.Cmder) (context.Context, error) {
  26. return h.spanStart(context.WithValue(ctx, startTimeKey, timex.Now())), nil
  27. }
  28. func (h hook) AfterProcess(ctx context.Context, cmd red.Cmder) error {
  29. h.spanEnd(ctx)
  30. val := ctx.Value(startTimeKey)
  31. if val == nil {
  32. return nil
  33. }
  34. start, ok := val.(time.Duration)
  35. if !ok {
  36. return nil
  37. }
  38. duration := timex.Since(start)
  39. if duration > slowThreshold.Load() {
  40. logDuration(ctx, cmd, duration)
  41. }
  42. return nil
  43. }
  44. func (h hook) BeforeProcessPipeline(ctx context.Context, _ []red.Cmder) (context.Context, error) {
  45. return h.spanStart(context.WithValue(ctx, startTimeKey, timex.Now())), nil
  46. }
  47. func (h hook) AfterProcessPipeline(ctx context.Context, cmds []red.Cmder) error {
  48. h.spanEnd(ctx)
  49. if len(cmds) == 0 {
  50. return nil
  51. }
  52. val := ctx.Value(startTimeKey)
  53. if val == nil {
  54. return nil
  55. }
  56. start, ok := val.(time.Duration)
  57. if !ok {
  58. return nil
  59. }
  60. duration := timex.Since(start)
  61. if duration > slowThreshold.Load()*time.Duration(len(cmds)) {
  62. logDuration(ctx, cmds[0], duration)
  63. }
  64. return nil
  65. }
  66. func logDuration(ctx context.Context, cmd red.Cmder, duration time.Duration) {
  67. var buf strings.Builder
  68. for i, arg := range cmd.Args() {
  69. if i > 0 {
  70. buf.WriteByte(' ')
  71. }
  72. buf.WriteString(mapping.Repr(arg))
  73. }
  74. logx.WithContext(ctx).WithDuration(duration).Slowf("[REDIS] slowcall on executing: %s", buf.String())
  75. }
  76. func (h hook) spanStart(ctx context.Context) context.Context {
  77. ctx, span := h.tracer.Start(ctx, "redis")
  78. return context.WithValue(ctx, spanKey, span)
  79. }
  80. func (h hook) spanEnd(ctx context.Context) {
  81. spanVal := ctx.Value(spanKey)
  82. if spanVal == nil {
  83. return
  84. }
  85. if span, ok := spanVal.(tracestd.Span); ok {
  86. span.End()
  87. }
  88. }