package middleware import ( "time" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gtime" ) // RequestLog 请求日志中间件 func RequestLog(r *ghttp.Request) { start := time.Now() // 记录请求开始 g.Log().Info(r.Context(), "请求开始", "method", r.Method, "uri", r.RequestURI, "ip", r.GetClientIp(), "user_agent", r.Header.Get("User-Agent"), ) r.Middleware.Next() // 记录请求结束 duration := time.Since(start) g.Log().Info(r.Context(), "请求结束", "method", r.Method, "uri", r.RequestURI, "status", r.Response.Status, "duration", duration.String(), "ip", r.GetClientIp(), ) } // ErrorLog 错误日志中间件 func ErrorLog(r *ghttp.Request) { r.Middleware.Next() // 如果有错误,记录详细信息 if r.Response.Status >= 400 { g.Log().Error(r.Context(), "请求错误", "method", r.Method, "uri", r.RequestURI, "status", r.Response.Status, "ip", r.GetClientIp(), "user_agent", r.Header.Get("User-Agent"), "time", gtime.Now().String(), ) } }