Golang使用映射的诊断上下文进行日志记录 [英] Golang Logging with Mapped Diagnostic Context
问题描述
如何实现 MDC Logging (Java)in GoLang?
我需要在所有服务器日志中添加UUID以便能够跟踪并发请求。
< Java MDC依靠线程本地存储,Go没有。
最接近的是通过您的堆栈来上下文。
这是越来越多的图书馆在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)//调用stdlib记录器
}
有很多方法可以处理这个问题,但这是一个相当简单的形式。
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.
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.
这篇关于Golang使用映射的诊断上下文进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!