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