github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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  	"github.com/hxx258456/ccgo/grpc"
    11  	"github.com/hxx258456/ccgo/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  // StreamServerInterceptor 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  func newClientLoggerFields(ctx context.Context, fullMethodString string) logrus.Fields {
    57  	service := path.Dir(fullMethodString)[1:]
    58  	method := path.Base(fullMethodString)
    59  	return logrus.Fields{
    60  		SystemField:    "grpc",
    61  		KindField:      "client",
    62  		"grpc.service": service,
    63  		"grpc.method":  method,
    64  	}
    65  }