logging.go 799 B

1234567891011121314151617181920212223242526272829303132333435
  1. package middleware
  2. import (
  3. "log"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // Logger is a middleware that logs HTTP requests
  8. func Logger(c *gin.Context) {
  9. start := time.Now()
  10. // Process request
  11. c.Next()
  12. // Log the request details
  13. duration := time.Since(start)
  14. statusCode := c.Writer.Status()
  15. method := c.Request.Method
  16. path := c.Request.URL.Path
  17. log.Printf("%s %s %d %s %s", method, path, statusCode, duration, c.ClientIP())
  18. if statusCode >= 400 {
  19. log.Printf("Error: %s %s %d", method, path, statusCode)
  20. }
  21. // Log the response size
  22. responseSize := c.Writer.Size()
  23. log.Printf("Response size: %d bytes", responseSize)
  24. // Log the request duration
  25. log.Printf("Request duration: %s", duration)
  26. // Log the client IP
  27. clientIP := c.ClientIP()
  28. log.Printf("Client IP: %s", clientIP)
  29. }