authorizer/server/middlewares/log.go

79 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-05-12 19:17:01 +00:00
package middlewares
import (
"fmt"
2022-05-25 09:34:26 +00:00
"math"
"net/http"
"os"
2022-05-12 19:17:01 +00:00
"time"
"github.com/gin-gonic/gin"
2022-05-25 09:34:26 +00:00
"github.com/sirupsen/logrus"
2022-05-12 19:17:01 +00:00
)
2022-05-25 09:34:26 +00:00
var timeFormat = "02/Jan/2006:15:04:05 -0700"
2022-05-12 19:17:01 +00:00
2022-05-25 09:34:26 +00:00
// Logger is the logrus logger handler
func Logger(logger logrus.FieldLogger, notLogged ...string) gin.HandlerFunc {
hostname, err := os.Hostname()
if err != nil {
hostname = "unknown"
}
2022-05-12 19:17:01 +00:00
2022-05-25 09:34:26 +00: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{}{}
}
}
2022-05-12 19:17:01 +00:00
return func(c *gin.Context) {
2022-05-25 09:34:26 +00:00
// other handler can change c.Path so:
path := c.Request.URL.Path
2022-05-12 19:17:01 +00:00
start := time.Now()
c.Next()
2022-05-25 09:34:26 +00:00
stop := time.Since(start)
latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
statusCode := c.Writer.Status()
clientIP := c.ClientIP()
clientUserAgent := c.Request.UserAgent()
referer := c.Request.Referer()
dataLength := c.Writer.Size()
if dataLength < 0 {
dataLength = 0
}
if _, ok := skip[path]; ok {
return
}
2022-05-12 19:17:01 +00:00
2022-05-25 09:34:26 +00:00
entry := logger.WithFields(logrus.Fields{
"hostname": hostname,
"statusCode": statusCode,
"latency": latency, // time to process
"clientIP": clientIP,
"method": c.Request.Method,
"path": path,
"referer": referer,
"dataLength": dataLength,
"userAgent": clientUserAgent,
2022-05-12 19:17:01 +00:00
})
2022-05-25 09:34:26 +00:00
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
2022-05-12 19:17:01 +00:00
} else {
2022-05-25 09:34:26 +00: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)
if statusCode >= http.StatusInternalServerError {
entry.Error(msg)
} else if statusCode >= http.StatusBadRequest {
entry.Warn(msg)
} else {
entry.Info(msg)
}
2022-05-12 19:17:01 +00:00
}
}
}