gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/logging/zap/client_interceptors.go (about) 1 // Copyright 2017 Michal Witkowski. All Rights Reserved. 2 // See LICENSE for licensing terms. 3 4 package grpc_zap 5 6 import ( 7 "path" 8 "time" 9 10 "gitee.com/ks-custle/core-gm/grpc" 11 "gitee.com/ks-custle/core-gm/net/context" 12 "go.uber.org/zap" 13 "go.uber.org/zap/zapcore" 14 ) 15 16 var ( 17 // ClientField is used in every client-side log statement made through grpc_zap. Can be overwritten before initialization. 18 ClientField = zap.String("span.kind", "client") 19 ) 20 21 // UnaryClientInterceptor returns a new unary client interceptor that optionally logs the execution of external gRPC calls. 22 func UnaryClientInterceptor(logger *zap.Logger, opts ...Option) grpc.UnaryClientInterceptor { 23 o := evaluateClientOpt(opts) 24 return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { 25 fields := newClientLoggerFields(ctx, method) 26 startTime := time.Now() 27 err := invoker(ctx, method, req, reply, cc, opts...) 28 logFinalClientLine(o, logger.With(fields...), startTime, err, "finished client unary call") 29 return err 30 } 31 } 32 33 // StreamClientInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls. 34 func StreamClientInterceptor(logger *zap.Logger, opts ...Option) grpc.StreamClientInterceptor { 35 o := evaluateClientOpt(opts) 36 return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { 37 fields := newClientLoggerFields(ctx, method) 38 startTime := time.Now() 39 clientStream, err := streamer(ctx, desc, cc, method, opts...) 40 logFinalClientLine(o, logger.With(fields...), startTime, err, "finished client streaming call") 41 return clientStream, err 42 } 43 } 44 45 func logFinalClientLine(o *options, logger *zap.Logger, startTime time.Time, err error, msg string) { 46 code := o.codeFunc(err) 47 level := o.levelFunc(code) 48 logger.Check(level, msg).Write( 49 zap.Error(err), 50 zap.String("grpc.code", code.String()), 51 o.durationFunc(time.Now().Sub(startTime)), 52 ) 53 } 54 55 //goland:noinspection GoUnusedParameter 56 func newClientLoggerFields(ctx context.Context, fullMethodString string) []zapcore.Field { 57 service := path.Dir(fullMethodString)[1:] 58 method := path.Base(fullMethodString) 59 return []zapcore.Field{ 60 SystemField, 61 ClientField, 62 zap.String("grpc.service", service), 63 zap.String("grpc.method", method), 64 } 65 }