我是靠谱客的博主 烂漫时光,最近开发中收集的这篇文章主要介绍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.

最后

以上就是烂漫时光为你收集整理的golang日志服务器_Golang使用映射的诊断上下文进行日志记录的全部内容,希望文章能够帮你解决golang日志服务器_Golang使用映射的诊断上下文进行日志记录所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(32)

评论列表共有 0 条评论

立即
投稿
返回
顶部