2021-11-26 10:50:56 +02:00
|
|
|
package middleware
|
2021-08-30 19:14:04 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2021-10-12 09:25:13 +02:00
|
|
|
"github.com/rs/zerolog/log"
|
2021-08-30 19:14:04 +02:00
|
|
|
)
|
|
|
|
|
2021-10-12 09:25:13 +02:00
|
|
|
// Logger returns a gin.HandlerFunc (middleware) that logs requests using zerolog.
|
2021-08-30 19:14:04 +02:00
|
|
|
//
|
2021-10-12 09:25:13 +02:00
|
|
|
// Requests with errors are logged using log.Err().
|
|
|
|
// Requests without errors are logged using log.Info().
|
2021-08-30 19:14:04 +02:00
|
|
|
//
|
|
|
|
// It receives:
|
|
|
|
// 1. A time package format string (e.g. time.RFC3339).
|
|
|
|
// 2. A boolean stating whether to use UTC time zone or local.
|
2021-10-12 09:25:13 +02:00
|
|
|
func Logger(timeFormat string, utc bool) gin.HandlerFunc {
|
2021-08-30 19:14:04 +02:00
|
|
|
return func(c *gin.Context) {
|
|
|
|
start := time.Now()
|
|
|
|
// some evil middlewares modify this values
|
|
|
|
path := c.Request.URL.Path
|
|
|
|
c.Next()
|
|
|
|
|
|
|
|
end := time.Now()
|
|
|
|
latency := end.Sub(start)
|
|
|
|
if utc {
|
|
|
|
end = end.UTC()
|
|
|
|
}
|
|
|
|
|
2021-10-12 09:25:13 +02:00
|
|
|
entry := map[string]interface{}{
|
2021-08-30 19:14:04 +02:00
|
|
|
"status": c.Writer.Status(),
|
|
|
|
"method": c.Request.Method,
|
|
|
|
"path": path,
|
|
|
|
"ip": c.ClientIP(),
|
|
|
|
"latency": latency,
|
|
|
|
"user-agent": c.Request.UserAgent(),
|
|
|
|
"time": end.Format(timeFormat),
|
2021-10-12 09:25:13 +02:00
|
|
|
}
|
2021-08-30 19:14:04 +02:00
|
|
|
|
|
|
|
if len(c.Errors) > 0 {
|
|
|
|
// Append error field if this is an erroneous request.
|
2021-10-12 09:25:13 +02:00
|
|
|
log.Error().Str("error", c.Errors.String()).Fields(entry).Msg("")
|
2021-08-30 19:14:04 +02:00
|
|
|
} else {
|
2021-10-12 09:25:13 +02:00
|
|
|
log.Info().Fields(entry).Msg("")
|
2021-08-30 19:14:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|