go - 处理程序服务后,如何从请求对象取回记录器对象?

标签 go logging gorilla logrus

我正在尝试学习如何在Go中使用中间件。
我成功将带有请求上下文的logger对象发送到处理程序函数。
但是,一旦处理了请求,并且记录程序对象被处理程序函数中的数据/错误填充,我希望能够访问修改后的对象。但是根据我当前的实现,我得到了一个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"}
期望从处理程序函数中添加“错误”字段。
我知道在这种情况下存在一些概念上的错误,但无法解决。
因此,基本上,我只想一次记录所有内容,而不是多次记录,因为这只需要获取最终字段和所有内容就在中间件上。

最佳答案

如果目的是访问修改后的记录器,则只需使用在该中间件中创建的记录器实例,而不必从响应中找回它。但是,这就是您的代码无法正常工作的原因:

m := httpsnoop.CaptureMetrics(next, w, r.WithContext(ctx))
WithContext返回具有新上下文的新请求。旧请求未修改。改为这样做:
r=r.WithContext(ctx)
m := httpsnoop.CaptureMetrics(next, w, r)
这会将包含新上下文的新请求分配给r。继续使用新的r访问修改后的请求和上下文。

关于go - 处理程序服务后,如何从请求对象取回记录器对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63117717/

相关文章:

database - aerospike-go 库中的嵌入式结构意外行为

mysql - 在 MySQL 中截断慢查询日志

python - TimedRotatingFileHandler 在具有多实例的 Django 中不能正常工作

logging - 带通配符的 Logback 记录器名称

当 SessionStore 来自导出包时未设置 Gorilla/sessions cookie

reactjs - 如何设置服务 reactjs 应用程序的路由?

go - 使用整数作为小数系数而不是 float 对于货币应用来说是个好主意吗?

json - Go:如何将响应体变成请求体?

go - 使用嵌入式 core.v1.PodSpec 验证 CRD

go - 在 Golang 中处理 URL 中的动态参数