golang日志服务器_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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值