github.com/jasonish/buffalo@v0.8.2-0.20170413145823-bacbdd415f1b/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 ct := c.Request().Header.Get("Content-Type") 35 if ct != "" { 36 c.LogField("content_type", ct) 37 } 38 defer func() { 39 ws := c.Response().(*buffaloResponse) 40 c.LogFields(logrus.Fields{ 41 "duration": time.Now().Sub(now), 42 "size": ws.size, 43 "human_size": humanize.Bytes(uint64(ws.size)), 44 "status": ws.status, 45 }) 46 c.Logger().Info() 47 }() 48 return h(c) 49 } 50 }