statinterceptor.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. } else {
  55. logger.Infof("%s - %s", addr, method)
  56. }
  57. } else {
  58. content, err := json.Marshal(req)
  59. if err != nil {
  60. logx.WithContext(ctx).Errorf("%s - %s", addr, err.Error())
  61. } else if duration > slowThreshold.Load() {
  62. logger.Slowf("[RPC] slowcall - %s - %s - %s", addr, method, string(content))
  63. } else {
  64. logger.Infof("%s - %s - %s", addr, method, string(content))
  65. }
  66. }
  67. }