github.com/ashleymcnamara/buffalo@v0.8.0/request_logger.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/Sirupsen/logrus"
     7  	humanize "github.com/dustin/go-humanize"
     8  	"github.com/markbates/going/randx"
     9  )
    10  
    11  // RequestLogger can be be overridden to a user specified
    12  // function that can be used to log the request.
    13  var RequestLogger = RequestLoggerFunc
    14  
    15  // RequestLoggerFunc is the default implementation of the RequestLogger.
    16  // By default it will log a uniq "request_id", the HTTP Method of the request,
    17  // the path that was requested, the duration (time) it took to process the
    18  // request, the size of the response (and the "human" size), and the status
    19  // code of the response.
    20  func RequestLoggerFunc(h Handler) Handler {
    21  	return func(c Context) error {
    22  		var irid interface{}
    23  		if irid = c.Session().Get("requestor_id"); irid == nil {
    24  			irid = randx.String(10)
    25  			c.Session().Set("requestor_id", irid)
    26  			c.Session().Save()
    27  		}
    28  		now := time.Now()
    29  		c.LogFields(logrus.Fields{
    30  			"request_id": irid.(string) + "-" + randx.String(10),
    31  			"method":     c.Request().Method,
    32  			"path":       c.Request().URL.String(),
    33  		})
    34  		defer func() {
    35  			ws := c.Response().(*buffaloResponse)
    36  			c.LogFields(logrus.Fields{
    37  				"duration":   time.Now().Sub(now),
    38  				"size":       ws.size,
    39  				"human_size": humanize.Bytes(uint64(ws.size)),
    40  				"status":     ws.status,
    41  			})
    42  			c.Logger().Info()
    43  		}()
    44  		return h(c)
    45  	}
    46  }