Files
MyClub/internal/middleware/request_logger.go
T
Tomas Dvorak b9cea0cd77 dev day #79
2025-11-02 01:04:02 +01:00

37 lines
1.0 KiB
Go

package middleware
import (
"time"
"fotbal-club/pkg/logger"
"github.com/gin-gonic/gin"
)
// RequestLogger logs a concise access log line per request with latency and identifiers.
// It is lightweight and safe for production usage.
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
method := c.Request.Method
// Continue
c.Next()
// After handler
status := c.Writer.Status()
latency := time.Since(start)
rid := c.GetString("request_id")
// Try both userID keys used across codebase
var uid any
if v, ok := c.Get("userID"); ok {
uid = v
} else if v, ok := c.Get("user_id"); ok {
uid = v
}
if uid != nil {
logger.Info("%s %s => %d (%s) rid=%s uid=%v", method, path, status, latency, rid, uid)
} else {
logger.Info("%s %s => %d (%s) rid=%s", method, path, status, latency, rid)
}
}
}