pcgamedb/server/middleware/log.go

73 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-09-24 06:17:11 -04:00
package middleware
import (
2024-12-10 08:37:16 -05:00
"pcgamedb/log"
2024-11-14 06:22:52 -05:00
"strings"
2024-09-24 06:17:11 -04:00
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
2024-12-10 08:37:16 -05:00
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
2024-09-24 06:17:11 -04:00
c.Next()
2024-12-10 08:37:16 -05:00
if shouldSkipLog(path) {
2024-11-14 06:22:52 -05:00
return
}
2024-12-10 08:37:16 -05:00
if raw != "" {
path = path + "?" + raw
}
fields := []zap.Field{
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("ip", getRealIP(c)),
zap.Duration("latency", time.Since(startTime)),
}
2024-09-24 06:17:11 -04:00
if len(c.Errors) > 0 {
2024-12-10 08:37:16 -05:00
fields = append(fields, zap.Strings("errors", c.Errors.Errors()))
}
log.Logger.Info("Request", fields...)
}
}
func getRealIP(c *gin.Context) string {
if ip := c.GetHeader("X-Real-IP"); ip != "" {
return ip
}
if ip := c.GetHeader("X-Forwarded-For"); ip != "" {
if index := strings.Index(ip, ","); index != -1 {
return strings.TrimSpace(ip[:index])
}
return ip
}
if ip := c.GetHeader("X-Originating-IP"); ip != "" {
return ip
}
return c.ClientIP()
}
func shouldSkipLog(path string) bool {
skipPaths := []string{
"/swagger/",
"/favicon.ico",
"/health",
}
for _, p := range skipPaths {
if strings.HasPrefix(path, p) {
return true
2024-09-24 06:17:11 -04:00
}
}
2024-12-10 08:37:16 -05:00
return false
2024-09-24 06:17:11 -04:00
}