package middleware import ( "fmt" "time" "git.linuxforward.com/byom/byom-core-gateway/logger" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) // RequestLogger middleware logs details about each request func RequestLogger(log *logrus.Logger) gin.HandlerFunc { requestLogger := logger.NewLogger("request") return func(c *gin.Context) { // Start timer start := time.Now() // Get request ID requestID := c.GetString(RequestIDKey) if requestID == "" { requestID = "no-request-id" } // Add request ID to logger reqLogger := logger.WithRequestID(requestLogger, requestID) // Process request c.Next() // Calculate latency latency := time.Since(start) // Get path and status path := c.Request.URL.Path if raw := c.Request.URL.RawQuery; raw != "" { path = fmt.Sprintf("%s?%s", path, raw) } // Log request details reqLogger.WithFields(logrus.Fields{ "method": c.Request.Method, "path": path, "status": c.Writer.Status(), "latency_ms": float64(latency.Nanoseconds()) / 1e6, "client_ip": c.ClientIP(), "user_agent": c.Request.UserAgent(), }).Info("Request processed") // If there was an error, log it with the error field if len(c.Errors) > 0 { reqLogger.WithField("errors", c.Errors.String()).Error("Request errors") } } }