statinterceptor.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "encoding/json"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "github.com/zeromicro/go-zero/core/stat"
  8. "github.com/zeromicro/go-zero/core/syncx"
  9. "github.com/zeromicro/go-zero/core/timex"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/peer"
  12. )
  13. const defaultSlowThreshold = time.Millisecond * 500
  14. var slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
  15. // SetSlowThreshold sets the slow threshold.
  16. func SetSlowThreshold(threshold time.Duration) {
  17. slowThreshold.Set(threshold)
  18. }
  19. // UnaryStatInterceptor returns a func that uses given metrics to report stats.
  20. func UnaryStatInterceptor(metrics *stat.Metrics) grpc.UnaryServerInterceptor {
  21. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  22. handler grpc.UnaryHandler) (resp interface{}, err error) {
  23. startTime := timex.Now()
  24. defer func() {
  25. duration := timex.Since(startTime)
  26. metrics.Add(stat.Task{
  27. Duration: duration,
  28. })
  29. logDuration(ctx, info.FullMethod, req, duration)
  30. }()
  31. return handler(ctx, req)
  32. }
  33. }
  34. func logDuration(ctx context.Context, method string, req interface{}, duration time.Duration) {
  35. var addr string
  36. client, ok := peer.FromContext(ctx)
  37. if ok {
  38. addr = client.Addr.String()
  39. }
  40. content, err := json.Marshal(req)
  41. if err != nil {
  42. logx.WithContext(ctx).Errorf("%s - %s", addr, err.Error())
  43. } else if duration > slowThreshold.Load() {
  44. logx.WithContext(ctx).WithDuration(duration).Slowf("[RPC] slowcall - %s - %s - %s",
  45. addr, method, string(content))
  46. } else {
  47. logx.WithContext(ctx).WithDuration(duration).Infof("%s - %s - %s", addr, method, string(content))
  48. }
  49. }