durationinterceptor.go 1.2 KB

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