statinterceptor.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. defer handleCrash(func(r interface{}) {
  24. err = toPanicError(r)
  25. })
  26. startTime := timex.Now()
  27. defer func() {
  28. duration := timex.Since(startTime)
  29. metrics.Add(stat.Task{
  30. Duration: duration,
  31. })
  32. logDuration(ctx, info.FullMethod, req, duration)
  33. }()
  34. return handler(ctx, req)
  35. }
  36. }
  37. func logDuration(ctx context.Context, method string, req interface{}, duration time.Duration) {
  38. var addr string
  39. client, ok := peer.FromContext(ctx)
  40. if ok {
  41. addr = client.Addr.String()
  42. }
  43. content, err := json.Marshal(req)
  44. if err != nil {
  45. logx.WithContext(ctx).Errorf("%s - %s", addr, err.Error())
  46. } else if duration > slowThreshold.Load() {
  47. logx.WithContext(ctx).WithDuration(duration).Slowf("[RPC] slowcall - %s - %s - %s",
  48. addr, method, string(content))
  49. } else {
  50. logx.WithContext(ctx).WithDuration(duration).Infof("%s - %s - %s", addr, method, string(content))
  51. }
  52. }