pcgamedb/server/middleware/log.go

48 lines
896 B
Go
Raw Normal View History

2024-09-24 06:17:11 -04:00
package middleware
import (
"strconv"
2024-11-14 06:22:52 -05:00
"strings"
2024-09-24 06:17:11 -04:00
"time"
2024-11-15 02:02:45 -05:00
"github.com/nitezs/pcgamedb/log"
2024-09-24 06:17:11 -04:00
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
c.Next()
endTime := time.Now()
latencyTime := endTime.Sub(startTime).Milliseconds()
reqMethod := c.Request.Method
reqURI := c.Request.RequestURI
statusCode := c.Writer.Status()
clientIP := c.ClientIP()
2024-11-14 06:22:52 -05:00
if strings.HasPrefix(reqURI, "/swagger/") ||
strings.EqualFold(reqURI, "/favicon.ico") {
return
}
2024-09-24 06:17:11 -04:00
log.Logger.Info(
"request",
zap.Int("code", statusCode),
zap.String("method", reqMethod),
zap.String("uri", reqURI),
zap.String("ip", clientIP),
zap.String("latency", strconv.Itoa(int(latencyTime))+"ms"),
)
if len(c.Errors) > 0 {
for _, e := range c.Errors.Errors() {
log.Logger.Error(e)
}
}
}
}