...

Source file src/github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus/context.go

Documentation: github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus

     1  package ctxlogrus
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/grpc-ecosystem/go-grpc-middleware/tags"
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  type ctxLoggerMarker struct{}
    11  
    12  type ctxLogger struct {
    13  	logger *logrus.Entry
    14  	fields logrus.Fields
    15  }
    16  
    17  var (
    18  	ctxLoggerKey = &ctxLoggerMarker{}
    19  )
    20  
    21  // AddFields adds logrus fields to the logger.
    22  func AddFields(ctx context.Context, fields logrus.Fields) {
    23  	l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger)
    24  	if !ok || l == nil {
    25  		return
    26  	}
    27  	for k, v := range fields {
    28  		l.fields[k] = v
    29  	}
    30  }
    31  
    32  // Extract takes the call-scoped logrus.Entry from ctx_logrus middleware.
    33  //
    34  // If the ctx_logrus middleware wasn't used, a no-op `logrus.Entry` is returned. This makes it safe to
    35  // use regardless.
    36  func Extract(ctx context.Context) *logrus.Entry {
    37  	l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger)
    38  	if !ok || l == nil {
    39  		return logrus.NewEntry(nullLogger)
    40  	}
    41  
    42  	fields := logrus.Fields{}
    43  
    44  	// Add grpc_ctxtags tags metadata until now.
    45  	tags := grpc_ctxtags.Extract(ctx)
    46  	for k, v := range tags.Values() {
    47  		fields[k] = v
    48  	}
    49  
    50  	// Add logrus fields added until now.
    51  	for k, v := range l.fields {
    52  		fields[k] = v
    53  	}
    54  
    55  	return l.logger.WithFields(fields)
    56  }
    57  
    58  // ToContext adds the logrus.Entry to the context for extraction later.
    59  // Returning the new context that has been created.
    60  func ToContext(ctx context.Context, entry *logrus.Entry) context.Context {
    61  	l := &ctxLogger{
    62  		logger: entry,
    63  		fields: logrus.Fields{},
    64  	}
    65  	return context.WithValue(ctx, ctxLoggerKey, l)
    66  }
    67  

View as plain text