logger.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package middleware
  2. import (
  3. "box-cost/db"
  4. "box-cost/db/model"
  5. "box-cost/db/repo"
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "log"
  11. "strings"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // 记录日志
  16. func Logger() gin.HandlerFunc {
  17. return func(c *gin.Context) {
  18. if strings.Contains(c.Request.URL.Path, "/update") {
  19. c.Next()
  20. return
  21. }
  22. // 处理请求
  23. var requestBody bytes.Buffer
  24. requestBodyBytes, err := io.ReadAll(c.Request.Body)
  25. if err != nil {
  26. log.Printf("Error reading body: %v", err)
  27. return
  28. }
  29. requestBody.Write(requestBodyBytes)
  30. c.Request.Body = io.NopCloser(&requestBody)
  31. reqb := requestBody.String()
  32. // 记录响应 body
  33. // var responseBody bytes.Buffer
  34. // writer := io.MultiWriter(c.Writer, &responseBody)
  35. // c.Writer = &bodyLogWriter{body: &responseBody, ResponseWriter: c.Writer, writer: writer}
  36. // 其他中间件执行,洋葱模型
  37. // 开始时间
  38. start := time.Now()
  39. c.Next()
  40. // 结束时间
  41. // resb := responseBody.String()
  42. session := &repo.RepoSession{
  43. Ctx: context.Background(),
  44. Client: db.MongoClient,
  45. }
  46. id, err := CreateLog(start, reqb, "", session, c)
  47. if err != nil {
  48. fmt.Println(err)
  49. }
  50. fmt.Println("request_log_id: ", id)
  51. }
  52. }
  53. func CreateLog(start time.Time, reqb string, resb string, session *repo.RepoSession, c *gin.Context) (string, error) {
  54. _time := time.Since(start).Seconds()
  55. path := c.Request.URL.Path
  56. method := c.Request.Method
  57. ip := c.ClientIP()
  58. code := c.Writer.Status()
  59. query := c.Request.URL.RawQuery
  60. _id, _ := c.Get("userId")
  61. id := ""
  62. if _id == nil {
  63. id = ""
  64. } else {
  65. id = _id.(string)
  66. }
  67. requesLogs := &model.RequestLogs{
  68. UserId: id,
  69. Path: path,
  70. Method: method,
  71. Ip: ip,
  72. Code: code,
  73. Time: _time * 1000, // ms
  74. Query: query,
  75. Reqbody: reqb,
  76. Resbody: resb,
  77. CreateTime: time.Now(),
  78. }
  79. return repo.RepoAddDoc(session, repo.CollectionRequestLogs, requesLogs)
  80. }
  81. // type bodyLogWriter struct {
  82. // gin.ResponseWriter
  83. // body *bytes.Buffer
  84. // writer io.Writer
  85. // }
  86. // func (w bodyLogWriter) Write(b []byte) (int, error) {
  87. // return w.writer.Write(b)
  88. // }