github.com/fedir/buffalo@v0.11.1/request_logger.go (about)

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