go-zero/zrpc/internal/clientinterceptors/durationinterceptor.go

33 lines
862 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package clientinterceptors
import (
"context"
"path"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/timex"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
)
const slowThreshold = time.Millisecond * 500
func DurationInterceptor(ctx context.Context, method string, req, reply interface{},
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
serverName := path.Join(cc.Target(), method)
start := timex.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
logx.WithContext(ctx).WithDuration(timex.Since(start)).Infof("fail - %s - %v - %s",
serverName, req, err.Error())
2020-07-26 17:09:05 +08:00
} else {
elapsed := timex.Since(start)
if elapsed > slowThreshold {
logx.WithContext(ctx).WithDuration(elapsed).Slowf("[RPC] ok - slowcall - %s - %v - %v",
serverName, req, reply)
2020-07-26 17:09:05 +08:00
}
}
return err
}