request_logger.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package middleware
  2. import (
  3. "fmt"
  4. "time"
  5. "git.linuxforward.com/byom/byom-core/logger"
  6. "github.com/gin-gonic/gin"
  7. "github.com/sirupsen/logrus"
  8. )
  9. // RequestLogger middleware logs details about each request
  10. func RequestLogger(log *logrus.Logger) gin.HandlerFunc {
  11. requestLogger := logger.NewLogger("request")
  12. return func(c *gin.Context) {
  13. // Start timer
  14. start := time.Now()
  15. // Get request ID
  16. requestID := c.GetString(RequestIDKey)
  17. if requestID == "" {
  18. requestID = "no-request-id"
  19. }
  20. // Add request ID to logger
  21. reqLogger := logger.WithRequestID(requestLogger, requestID)
  22. // Process request
  23. c.Next()
  24. // Calculate latency
  25. latency := time.Since(start)
  26. // Get path and status
  27. path := c.Request.URL.Path
  28. if raw := c.Request.URL.RawQuery; raw != "" {
  29. path = fmt.Sprintf("%s?%s", path, raw)
  30. }
  31. // Log request details
  32. reqLogger.WithFields(logrus.Fields{
  33. "method": c.Request.Method,
  34. "path": path,
  35. "status": c.Writer.Status(),
  36. "latency_ms": float64(latency.Nanoseconds()) / 1e6,
  37. "client_ip": c.ClientIP(),
  38. "user_agent": c.Request.UserAgent(),
  39. }).Info("Request processed")
  40. // If there was an error, log it with the error field
  41. if len(c.Errors) > 0 {
  42. reqLogger.WithField("errors", c.Errors.String()).Error("Request errors")
  43. }
  44. }
  45. }