logger.go 679 B

123456789101112131415161718192021222324252627282930313233343536
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/sirupsen/logrus"
  5. "time"
  6. )
  7. func Logger() gin.HandlerFunc {
  8. return func(c *gin.Context) {
  9. // 记录请求开始时间
  10. start := time.Now()
  11. // 继续处理请求
  12. c.Next()
  13. // 记录请求结束时间
  14. end := time.Now()
  15. latency := end.Sub(start)
  16. // 获取请求方法和路径
  17. method := c.Request.Method
  18. path := c.Request.URL.Path
  19. // 获取响应状态码
  20. statusCode := c.Writer.Status()
  21. // 记录日志
  22. logrus.WithFields(logrus.Fields{
  23. "status_code": statusCode,
  24. "latency": latency,
  25. "method": method,
  26. "path": path,
  27. }).Info("Request processed")
  28. }
  29. }