Golang使用Mapped Diagnostic Context进行日志记录

huangapple go评论75阅读模式
英文:

Golang Logging with Mapped Diagnostic Context

问题

我可以帮你翻译。以下是翻译的内容:

如何在Go语言中实现MDC Logging

为了能够跟踪并发请求,我需要在所有服务器日志中添加UUID。

英文:

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

得分: 12

Java MDC依赖于线程本地存储,而Go语言没有这个功能。

最接近的方法是通过堆栈传递Context。这是越来越多的Go库所采用的方式。

一个比较典型的方式是通过中间件包将请求ID添加到Web请求的上下文中,例如:

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

然后,假设你在上下文中传递了这个请求,你可以使用ctx.Value("requestId")来提取它,并在合适的地方使用它。

你可能还想创建自己的自定义日志记录函数,例如:

func logStuff(ctx context.Context, msg string) {
    log.Println(ctx.Value("requestId"), msg) // 调用标准库的日志记录器
}

处理这个问题的方式有很多种,但这是一个相对简单的形式。

英文:

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.

huangapple
  • 本文由 发表于 2016年12月9日 05:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/41048757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定