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

47 lines
1.1 KiB
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
)
2024-09-19 18:05:16 +03:00
// GinMiddleware will construct Gin middleware which will log requests and provide logger with unique request ID.
2023-10-18 18:16:59 +03:00
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
2024-09-19 18:05:16 +03:00
streamID := generateStreamID()
log := log.With(StreamID(streamID))
c.Set(StreamIDAttr, streamID)
c.Set("logger", log)
2023-10-18 18:16:59 +03:00
// 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
)
}
}
2024-09-19 18:05:16 +03:00
func MustGet(c *gin.Context) Logger {
return c.MustGet("logger").(Logger)
}