user_logger.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package middleware
  2. import (
  3. "app/commons/core"
  4. "app/commons/model/entity"
  5. "bytes"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "io"
  9. "time"
  10. )
  11. func UserLogger() gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. // 开始时间
  14. start := time.Now()
  15. // 记录请求信息
  16. clientIP := c.ClientIP()
  17. method := c.Request.Method
  18. path := c.Request.URL.Path
  19. query := c.Request.URL.RawQuery
  20. // 读取请求体
  21. var requestBody []byte
  22. if c.Request.Body != nil {
  23. requestBody, _ = io.ReadAll(c.Request.Body)
  24. // 读取后重新赋值,因为读取后body会被清空
  25. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  26. }
  27. // 创建一个自定义的 ResponseWriter 来捕获响应
  28. blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
  29. c.Writer = blw
  30. c.Next()
  31. // 在请求结束时记录日志
  32. elapsed := time.Since(start)
  33. core.Log.Infof("GIN|%d|%s|IP:%s|%s|URI:%s|",
  34. c.Writer.Status(),
  35. elapsed.Round(time.Millisecond),
  36. c.ClientIP(),
  37. c.Request.Method,
  38. c.Request.URL.Path)
  39. userId := c.GetInt64("userId")
  40. userLog := &entity.UserLogs{
  41. UserId: userId,
  42. UserAgent: c.Request.UserAgent(),
  43. Ip: clientIP,
  44. Action: method,
  45. Path: path,
  46. Query: query,
  47. Status: c.Writer.Status(),
  48. Request: string(requestBody),
  49. Response: blw.body.String(),
  50. Elapsed: fmt.Sprintf("%s", elapsed.Round(time.Millisecond)),
  51. }
  52. err := core.MainDb().Create(&userLog).Error
  53. if err != nil {
  54. core.Log.Error(err)
  55. }
  56. }
  57. }
  58. // bodyLogWriter 自定义ResponseWriter用于捕获响应体
  59. type bodyLogWriter struct {
  60. gin.ResponseWriter
  61. body *bytes.Buffer
  62. }
  63. func (w bodyLogWriter) Write(b []byte) (int, error) {
  64. w.body.Write(b)
  65. return w.ResponseWriter.Write(b)
  66. }