12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package middleware
- import (
- "box-cost/db"
- "box-cost/db/model"
- "box-cost/db/repo"
- "bytes"
- "context"
- "fmt"
- "io"
- "log"
- "strings"
- "time"
- "github.com/gin-gonic/gin"
- )
- // 记录日志
- func Logger() gin.HandlerFunc {
- return func(c *gin.Context) {
- if strings.Contains(c.Request.URL.Path, "/update") {
- c.Next()
- return
- }
- // 处理请求
- var requestBody bytes.Buffer
- requestBodyBytes, err := io.ReadAll(c.Request.Body)
- if err != nil {
- log.Printf("Error reading body: %v", err)
- return
- }
- requestBody.Write(requestBodyBytes)
- c.Request.Body = io.NopCloser(&requestBody)
- reqb := requestBody.String()
- // 记录响应 body
- // var responseBody bytes.Buffer
- // writer := io.MultiWriter(c.Writer, &responseBody)
- // c.Writer = &bodyLogWriter{body: &responseBody, ResponseWriter: c.Writer, writer: writer}
- // 其他中间件执行,洋葱模型
- // 开始时间
- start := time.Now()
- c.Next()
- // 结束时间
- // resb := responseBody.String()
- session := &repo.RepoSession{
- Ctx: context.Background(),
- Client: db.MongoClient,
- }
- id, err := CreateLog(start, reqb, "", session, c)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Println("request_log_id: ", id)
- }
- }
- func CreateLog(start time.Time, reqb string, resb string, session *repo.RepoSession, c *gin.Context) (string, error) {
- _time := time.Since(start).Seconds()
- path := c.Request.URL.Path
- method := c.Request.Method
- ip := c.ClientIP()
- code := c.Writer.Status()
- query := c.Request.URL.RawQuery
- id, _ := c.Get("userId")
- requesLogs := &model.RequestLogs{
- UserId: id.(string),
- Path: path,
- Method: method,
- Ip: ip,
- Code: code,
- Time: _time * 1000, // ms
- Query: query,
- Reqbody: reqb,
- Resbody: resb,
- CreateTime: time.Now(),
- }
- return repo.RepoAddDoc(session, repo.CollectionRequestLogs, requesLogs)
- }
- // type bodyLogWriter struct {
- // gin.ResponseWriter
- // body *bytes.Buffer
- // writer io.Writer
- // }
- // func (w bodyLogWriter) Write(b []byte) (int, error) {
- // return w.writer.Write(b)
- // }
|