github.com/furusax0621/goa-v1@v1.4.3/logging/logrus/adapter.go (about)

     1  /*
     2  Package goalogrus contains an adapter that makes it possible to configure goa so it uses logrus
     3  as logger backend.
     4  Usage:
     5  
     6      logger := logrus.New()
     7      // Initialize logger handler using logrus package
     8      service.WithLogger(goalogrus.New(logger))
     9      // ... Proceed with configuring and starting the goa service
    10  
    11      // In handlers:
    12      goalogrus.Entry(ctx).Info("foo", "bar")
    13  */
    14  package goalogrus
    15  
    16  import (
    17  	"fmt"
    18  
    19  	"context"
    20  
    21  	"github.com/goadesign/goa"
    22  	"github.com/sirupsen/logrus"
    23  )
    24  
    25  // adapter is the logrus goa logger adapter.
    26  type adapter struct {
    27  	*logrus.Entry
    28  }
    29  
    30  // New wraps a logrus logger into a goa logger.
    31  func New(logger *logrus.Logger) goa.LogAdapter {
    32  	return FromEntry(logrus.NewEntry(logger))
    33  }
    34  
    35  // FromEntry wraps a logrus log entry into a goa logger.
    36  func FromEntry(entry *logrus.Entry) goa.LogAdapter {
    37  	return &adapter{Entry: entry}
    38  }
    39  
    40  // Entry returns the logrus log entry stored in the given context if any, nil otherwise.
    41  func Entry(ctx context.Context) *logrus.Entry {
    42  	logger := goa.ContextLogger(ctx)
    43  	if a, ok := logger.(*adapter); ok {
    44  		return a.Entry
    45  	}
    46  	return nil
    47  }
    48  
    49  // Info logs messages using logrus.
    50  func (a *adapter) Info(msg string, data ...interface{}) {
    51  	a.Entry.WithFields(data2rus(data)).Info(msg)
    52  }
    53  
    54  // Error logs errors using logrus.
    55  func (a *adapter) Error(msg string, data ...interface{}) {
    56  	a.Entry.WithFields(data2rus(data)).Error(msg)
    57  }
    58  
    59  // New creates a new logger given a context.
    60  func (a *adapter) New(data ...interface{}) goa.LogAdapter {
    61  	return &adapter{Entry: a.Entry.WithFields(data2rus(data))}
    62  }
    63  
    64  func data2rus(keyvals []interface{}) logrus.Fields {
    65  	n := (len(keyvals) + 1) / 2
    66  	res := make(logrus.Fields, n)
    67  	for i := 0; i < len(keyvals); i += 2 {
    68  		k := keyvals[i]
    69  		var v interface{} = goa.ErrMissingLogValue
    70  		if i+1 < len(keyvals) {
    71  			v = keyvals[i+1]
    72  		}
    73  		res[fmt.Sprintf("%v", k)] = v
    74  	}
    75  	return res
    76  }