douchen5971 2016-12-08 21:03
浏览 228
已采纳

具有映射诊断上下文的Golang日志记录

How can I achieve MDC Logging (Java) in GoLang?

I need to add UUIDs in all server logs in order to be able to trace concurrent requests.

  • 写回答

1条回答 默认 最新

  • duanne9313 2016-12-08 21:47
    关注

    Java MDC relies on thread local storage, something Go does not have.

    The closest thing is to thread a Context through your stack.

    This is what more and more libraries are doing in Go.

    A somewhat typical way is to do this via a middleware package that adds a request id to the context of a web request, like:

    req = req.WithContext(context.WithValue(req.Context(),"requestId",ID))
    

    Then, assuming you pass the context around, you pull it out with ctx.Value("requestId") and use it wherever it makes sense.

    Possibly making your own custom logger function like:

    func logStuff(ctx context.Context, msg string) {
        log.Println(ctx.Value("requestId"),msg) // call stdlib logger
    }
    

    There's a bunch of ways you may want to handle this, but that's a fairly simple form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模数学建模需要
  • ¥15 c语言数据结构实验单链表的删除
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决