durationinterceptor.go 928 B

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