mg-transport-core/core/logger/gin.go

38 lines
834 B
Go
Raw Normal View History

2023-10-18 18:16:59 +03:00
package logger
import (
"time"
2023-11-24 15:23:07 +03:00
"github.com/gin-gonic/gin"
"go.uber.org/zap"
2023-10-18 18:16:59 +03:00
)
// GinMiddleware will construct Gin middleware which will log requests.
func GinMiddleware(log Logger) gin.HandlerFunc {
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// Process request
c.Next()
end := time.Now()
if raw != "" {
path = path + "?" + raw
}
2023-10-24 14:15:28 +03:00
log.Info("request",
2023-11-24 15:23:07 +03:00
zap.String(HandlerAttr, "GIN"),
zap.String("startTime", start.Format(time.RFC3339)),
zap.String("endTime", end.Format(time.RFC3339)),
zap.Any("latency", end.Sub(start)/time.Millisecond),
zap.String("remoteAddress", c.ClientIP()),
zap.String(HTTPMethodAttr, c.Request.Method),
zap.String("path", path),
zap.Int("bodySize", c.Writer.Size()),
2023-10-18 18:16:59 +03:00
)
}
}