middle.go 934 B

12345678910111213141516171819202122232425262728
  1. package service
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/net/ghttp"
  7. "github.com/gogf/gf/v2/util/gconv"
  8. "io"
  9. "time"
  10. )
  11. // Middleware 分析查询记录日志中间件
  12. // 获取请求时间、查询和响应
  13. // 记录查询到数据库、区分查询类型:简单查询、聚合查询、复杂查询
  14. // 根据es当前状态,使用4个通道,进行调度
  15. func Middleware(r *ghttp.Request) {
  16. now := time.Now()
  17. bodyBytes, err := io.ReadAll(r.Request.Body)
  18. if len(bodyBytes) > 0 && err == nil {
  19. finalBytes := bodyBytes
  20. r.ContentLength = gconv.Int64(len(finalBytes))
  21. r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
  22. r.Request.Body = io.NopCloser(bytes.NewReader(finalBytes))
  23. }
  24. r.Middleware.Next()
  25. g.Log().Infof(r.Context(), "status:%d time:%fs from:%s query:%s", r.Response.Status, time.Since(now).Seconds(), r.GetClientIp(), string(bodyBytes))
  26. }