gin-logrus/logger.go

85 lines
2.0 KiB
Go
Raw Normal View History

2016-09-26 17:22:16 +03:00
package ginlogrus
import (
"fmt"
"math"
2020-08-18 10:15:07 +03:00
"net/http"
2016-09-27 10:52:40 +03:00
"os"
2016-09-26 17:22:16 +03:00
"time"
"github.com/gin-gonic/gin"
2022-12-12 14:34:31 +03:00
"git.internal/re/logrus"
2016-09-26 17:22:16 +03:00
)
2016-09-27 10:52:40 +03:00
// 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"
2016-09-26 17:22:16 +03:00
// Logger is the logrus logger handler
2020-08-18 10:15:07 +03:00
func Logger(logger logrus.FieldLogger, notLogged ...string) gin.HandlerFunc {
2019-03-23 00:19:47 +03:00
hostname, err := os.Hostname()
if err != nil {
hostname = "unknow"
}
2020-08-18 10:15:07 +03:00
var skip map[string]struct{}
if length := len(notLogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, p := range notLogged {
skip[p] = struct{}{}
}
}
2016-09-26 17:22:16 +03:00
return func(c *gin.Context) {
// other handler can change c.Path so:
path := c.Request.URL.Path
start := time.Now()
c.Next()
stop := time.Since(start)
2018-06-29 09:49:33 +03:00
latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
2016-09-27 10:52:40 +03:00
statusCode := c.Writer.Status()
2016-09-26 17:22:16 +03:00
clientIP := c.ClientIP()
2016-09-27 10:52:40 +03:00
clientUserAgent := c.Request.UserAgent()
referer := c.Request.Referer()
dataLength := c.Writer.Size()
if dataLength < 0 {
dataLength = 0
}
2016-09-26 17:22:16 +03:00
2020-08-18 10:15:07 +03:00
if _, ok := skip[path]; ok {
return
}
entry := logger.WithFields(logrus.Fields{
2016-09-27 14:04:40 +03:00
"hostname": hostname,
2016-09-26 17:22:16 +03:00
"statusCode": statusCode,
"latency": latency, // time to process
"clientIP": clientIP,
"method": c.Request.Method,
"path": path,
2016-09-27 10:52:40 +03:00
"referer": referer,
"dataLength": dataLength,
"userAgent": clientUserAgent,
2016-09-26 17:22:16 +03:00
})
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
} else {
2016-09-27 10:52:40 +03:00
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)
2020-08-18 10:15:07 +03:00
if statusCode >= http.StatusInternalServerError {
2016-09-26 17:22:16 +03:00
entry.Error(msg)
2020-08-18 10:15:07 +03:00
} else if statusCode >= http.StatusBadRequest {
2016-09-26 17:22:16 +03:00
entry.Warn(msg)
} else {
entry.Info(msg)
}
}
}
}