首页 > 解决方案 > 如何从中间件记录响应正文?

问题描述

我试图从中间件记录响应正文。我可以获得与 Request 对象相关的所有数据。现在尝试记录单个请求的响应代码和响应正文。

我试图从 中捕获响应正文和响应代码w http.ResponseWriter,但未能成功。这是示例代码。我正在使用 go 的默认值httplogrus日志记录。

next.ServeHTTP(w, r.WithContext(ctx))
end := time.Now().UTC()
latency := end.Sub(start)
// request logging
log.WithFields(log.Fields{
    "path":      r.URL.Path,
    "method":    r.Method,
    "body":      body,
    "auth_user": claims,
    "latency":   latency,
    "useragent": r.Header.Get("User-Agent"),
    "response_body": ,// cannot get response body here
    "status": "", //cannot get response header here
}).Info("request data")

有人可以帮我吗?

标签: gologgingmiddleware

解决方案


推荐阅读