我正在尝试学习如何在 Go 中使用中间件。我成功地将带有请求上下文的记录器对象发送到处理程序函数。但是,一旦处理了请求并且记录器对象填充了来自处理函数的数据/错误,我希望能够访问修改后的对象。但根据我目前的实现,我得到一个 nil 对象。
logger := log.WithFields(log.Fields{
ReqIdKey: reqId,
"proto": r.Proto,
"method": r.Method,
"uri": r.URL.RequestURI(),
"startTime": time.Now(),
"body": t,
"header": r.Header,
"remote-addr": r.RemoteAddr,
})
ctx = context.WithValue(ctx, "logger", logger)
//Update as per suggestions recieved.
r = r.WithContext(ctx)
m := httpsnoop.CaptureMetrics(next, w, r)
//Post this point the internal functions modify the log and add errors etc extra fields which I want to access
//For example:
//logger := logcontext.GetLogCtx(ctx)
//logger = logger.WithFields(log.Fields{"error": err})
logger = logger.WithFields(log.Fields{
"responseTime": m.Duration,
"status": m.Code,
})
return logger.Info("Request Completed")
收到的回复:
{"body":null,"header":{"Accept":["*/*"],"Accept-Encoding":["gzip, deflate, br"],"Connection":["keep-alive"],"Postman-Token":["a1ef5d6c-94cb-4b64-b350-700c37eff6b4"],"User-Agent":["PostmanRuntime/7.26.2"]},"level":"info","method":"GET","msg":"Request completed","proto":"HTTP/1.1","remote-addr":"127.0.0.1:36254","responseTime":2463797,"startTime":"2020-07-28T00:31:22.97954465+05:30","status":503,"time":"2020-07-28T00:31:22+05:30","uri":"/api/v1/getSomething/some/xyz/abc/2","x-request-id":"f493a4ad-035c-48a8-9207-64a922c96961"}
期待处理函数中添加的“错误”字段。
我知道在这种情况下存在一些概念错误,但无法理解。
所以基本上我想记录所有内容一次,而不是多次,因为只需要在中间件中获取最终字段和所有内容。