electricity_bill_calc_service/logger/middleware.go

44 lines
725 B
Go

package logger
import (
"time"
"github.com/gin-gonic/gin"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// Process request
c.Next()
latency := time.Since(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
if raw != "" {
path = path + "?" + raw
}
event := logger.Info()
if comment != "" {
event = logger.Error()
}
event.
Int("statusCode", statusCode).
Dur("latency", latency).
Str("clientIP", clientIP).
Str("method", method).
Str("path", path).
Msg(comment)
}
}