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") id := "" if _id == nil { id = "" } else { id = _id.(string) } requesLogs := &model.RequestLogs{ UserId: id, 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) // }