From b1978c0b59932a8bf3837dec302a2d9046f5395a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Depierrepont=20aka=20Toorop?= Date: Tue, 27 Sep 2016 09:52:40 +0200 Subject: [PATCH] use apache log format --- logger.go | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/logger.go b/logger.go index 2cde142..2aab6a3 100644 --- a/logger.go +++ b/logger.go @@ -3,12 +3,21 @@ package ginlogrus import ( "fmt" "math" + "os" "time" "github.com/Sirupsen/logrus" "github.com/gin-gonic/gin" ) +// 2016-09-27 09:38:21.541541811 +0200 CEST +// 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] +// "GET /apache_pb.gif HTTP/1.0" 200 2326 +// "http://www.example.com/start.html" +// "Mozilla/4.08 [en] (Win98; I ;Nav)" + +var timeFormat = "02/Jan/2006:15:04:05 -0700" + // Logger is the logrus logger handler func Logger(log *logrus.Logger) gin.HandlerFunc { return func(c *gin.Context) { @@ -17,9 +26,19 @@ func Logger(log *logrus.Logger) gin.HandlerFunc { start := time.Now() c.Next() stop := time.Since(start) - statusCode := c.Writer.Status() latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000.0)) + statusCode := c.Writer.Status() clientIP := c.ClientIP() + clientUserAgent := c.Request.UserAgent() + referer := c.Request.Referer() + hostname, err := os.Hostname() + if err != nil { + hostname = "unknow" + } + dataLength := c.Writer.Size() + if dataLength < 0 { + dataLength = 0 + } entry := logrus.NewEntry(log).WithFields(logrus.Fields{ "statusCode": statusCode, @@ -27,13 +46,15 @@ func Logger(log *logrus.Logger) gin.HandlerFunc { "clientIP": clientIP, "method": c.Request.Method, "path": path, + "referer": referer, + "dataLength": dataLength, + "userAgent": clientUserAgent, }) if len(c.Errors) > 0 { entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String()) } else { - msg := fmt.Sprintf("%s - %s %s %d (%dms)", clientIP, c.Request.Method, path, statusCode, latency) - + msg := fmt.Sprintf("%s - %s [%s] \"%s %s\" %d %d \"%s\" \"%s\" (%dms)", clientIP, hostname, time.Now().Format(timeFormat), c.Request.Method, path, statusCode, dataLength, referer, clientUserAgent, latency) if statusCode > 499 { entry.Error(msg) } else if statusCode > 399 {