durationinterceptor.go 821 B

123456789101112131415161718192021222324252627282930
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "path"
  5. "time"
  6. "github.com/tal-tech/go-zero/core/logx"
  7. "github.com/tal-tech/go-zero/core/timex"
  8. "google.golang.org/grpc"
  9. )
  10. const slowThreshold = time.Millisecond * 500
  11. func DurationInterceptor(ctx context.Context, method string, req, reply interface{},
  12. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  13. serverName := path.Join(cc.Target(), method)
  14. start := timex.Now()
  15. err := invoker(ctx, method, req, reply, cc, opts...)
  16. if err != nil {
  17. logx.WithDuration(timex.Since(start)).Infof("fail - %s - %v - %s", serverName, req, err.Error())
  18. } else {
  19. elapsed := timex.Since(start)
  20. if elapsed > slowThreshold {
  21. logx.WithDuration(elapsed).Slowf("[RPC] ok - slowcall - %s - %v - %v", serverName, req, reply)
  22. }
  23. }
  24. return err
  25. }