statinterceptor.go 1.4 KB

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