github.com/xmidt-org/webpa-common@v1.11.9/middleware/logging.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/go-kit/kit/endpoint"
     7  	"github.com/go-kit/kit/log"
     8  	"github.com/xmidt-org/webpa-common/logging"
     9  )
    10  
    11  // loggable is the interface implemented by any message object which is associated with a go-kit Logger
    12  type loggable interface {
    13  	Logger() log.Logger
    14  }
    15  
    16  // Logging is a go-kit middleware that inserts any associated logger from requests into the context.
    17  // Requests that do not provide a Logger() log.Logger method are simply ignored.
    18  //
    19  // This middleware is primarily useful because go-kit does not allow you to alter the context when requests
    20  // are decoded.  That means that any contextual logger created when the request was decoded isn't visible
    21  // in the context, unless something like this middleware is used.
    22  func Logging(next endpoint.Endpoint) endpoint.Endpoint {
    23  	return func(ctx context.Context, value interface{}) (interface{}, error) {
    24  		if l, ok := value.(loggable); ok {
    25  			return next(
    26  				logging.WithLogger(ctx, l.Logger()),
    27  				value,
    28  			)
    29  		}
    30  
    31  		return next(ctx, value)
    32  	}
    33  }