durationinterceptor.go 862 B

1234567891011121314151617181920212223242526272829303132
  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.WithContext(ctx).WithDuration(timex.Since(start)).Infof("fail - %s - %v - %s",
  18. serverName, req, err.Error())
  19. } else {
  20. elapsed := timex.Since(start)
  21. if elapsed > slowThreshold {
  22. logx.WithContext(ctx).WithDuration(elapsed).Slowf("[RPC] ok - slowcall - %s - %v - %v",
  23. serverName, req, reply)
  24. }
  25. }
  26. return err
  27. }