logger.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. requesLogs := &model.RequestLogs{
  62. UserId: id.(string),
  63. Path: path,
  64. Method: method,
  65. Ip: ip,
  66. Code: code,
  67. Time: _time * 1000, // ms
  68. Query: query,
  69. Reqbody: reqb,
  70. Resbody: resb,
  71. CreateTime: time.Now(),
  72. }
  73. return repo.RepoAddDoc(session, repo.CollectionRequestLogs, requesLogs)
  74. }
  75. // type bodyLogWriter struct {
  76. // gin.ResponseWriter
  77. // body *bytes.Buffer
  78. // writer io.Writer
  79. // }
  80. // func (w bodyLogWriter) Write(b []byte) (int, error) {
  81. // return w.writer.Write(b)
  82. // }