github.com/mayra-cabrera/buffalo@v0.9.4-0.20170814145312-66d2e7772f11/request_logger.go (about) 1 package buffalo 2 3 import ( 4 "time" 5 6 humanize "github.com/dustin/go-humanize" 7 "github.com/markbates/going/randx" 8 "github.com/sirupsen/logrus" 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 rid := irid.(string) + "-" + randx.String(10) 29 c.Set("request_id", rid) 30 c.LogField("request_id", rid) 31 32 start := time.Now() 33 defer func() { 34 ws := c.Response().(*Response) 35 ct := c.Request().Header.Get("Content-Type") 36 if ct != "" { 37 c.LogField("content_type", ct) 38 } 39 c.LogFields(logrus.Fields{ 40 "method": c.Request().Method, 41 "path": c.Request().URL.String(), 42 "duration": time.Since(start), 43 "size": ws.Size, 44 "human_size": humanize.Bytes(uint64(ws.Size)), 45 "status": ws.Status, 46 }) 47 c.Logger().Info(c.Request().URL.String()) 48 }() 49 return h(c) 50 } 51 }