statinterceptor.go 2.0 KB

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