package api
import (
"fmt"
"time"
"github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/jloup/utils"
)
var log = utils.StandardL().WithField("module", "api")
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
start := time.Now()
rawQuery := c.Request.URL.RawQuery
c.Next()
latency := time.Now().Sub(start).Round(10 * time.Microsecond)
code := c.Writer.Status()
l := log
l = l.WithField("latency", latency)
l = l.WithField("client_ip", c.ClientIP())
l = l.WithField("method", c.Request.Method)
l = l.WithField("status_code", code)
if _, exists := c.Get("user"); exists {
l = l.WithField("user_id", GetUser(c).Id)
}
if rawQuery != "" {
path = fmt.Sprintf("%s?%s", path, rawQuery)
}
l = l.WithField("path", path)
msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path)
var level logrus.Level
switch {
case code >= 200 && code < 400:
level = logrus.InfoLevel
case code >= 400 && code < 500:
level = logrus.WarnLevel
default:
level = logrus.ErrorLevel
}
errors := c.Errors.ByType(gin.ErrorTypePrivate)
for _, err := range errors {
l.Logf(level, "%s: %s", msgLog, err.Err)
}
if errors == nil {
l.Logf(level, msgLog)
}
}
}