Golang Logging with Mapped Diagnostic Context

ⅰ亾dé卋堺 提交于 2019-12-22 18:46:13

问题


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:


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.



来源:https://stackoverflow.com/questions/41048757/golang-logging-with-mapped-diagnostic-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!