gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/logging/logrus/client_interceptors.go (about) 1 // Copyright 2017 Michal Witkowski. All Rights Reserved. 2 // See LICENSE for licensing terms. 3 4 package grpc_logrus 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 "github.com/sirupsen/logrus" 13 ) 14 15 // UnaryClientInterceptor returns a new unary client interceptor that optionally logs the execution of external gRPC calls. 16 func UnaryClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryClientInterceptor { 17 o := evaluateClientOpt(opts) 18 return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { 19 fields := newClientLoggerFields(ctx, method) 20 startTime := time.Now() 21 err := invoker(ctx, method, req, reply, cc, opts...) 22 logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client unary call") 23 return err 24 } 25 } 26 27 // StreamClientInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls. 28 func StreamClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamClientInterceptor { 29 o := evaluateClientOpt(opts) 30 return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { 31 fields := newClientLoggerFields(ctx, method) 32 startTime := time.Now() 33 clientStream, err := streamer(ctx, desc, cc, method, opts...) 34 logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client streaming call") 35 return clientStream, err 36 } 37 } 38 39 func logFinalClientLine(o *options, entry *logrus.Entry, startTime time.Time, err error, msg string) { 40 code := o.codeFunc(err) 41 level := o.levelFunc(code) 42 durField, durVal := o.durationFunc(time.Now().Sub(startTime)) 43 fields := logrus.Fields{ 44 "grpc.code": code.String(), 45 durField: durVal, 46 } 47 if err != nil { 48 fields[logrus.ErrorKey] = err 49 } 50 levelLogf( 51 entry.WithFields(fields), 52 level, 53 msg) 54 } 55 56 //goland:noinspection GoUnusedParameter 57 func newClientLoggerFields(ctx context.Context, fullMethodString string) logrus.Fields { 58 service := path.Dir(fullMethodString)[1:] 59 method := path.Base(fullMethodString) 60 return logrus.Fields{ 61 SystemField: "grpc", 62 KindField: "client", 63 "grpc.service": service, 64 "grpc.method": method, 65 } 66 }