go - go微服务中如何给每条日志添加trace id

标签 go logging microservices trace

我想将跟踪 ID 添加到针对微服务的每个请求完成的日志记录中。我希望这与 springboot 应用程序类似,我们可以在 MDC 中设置跟踪 ID 并获取它并在日志记录时使用它。

我做了一些研究,发现 Go 语言中的 MDC 等价物是上下文。所以,我已经在我的上下文中设置了跟踪 ID。现在的问题是我必须使用跟踪 ID 登录的地方,我需要将上下文传递给该函数,这是非常丑陋的方式。我正在为这个问题寻找更好的解决方案。

func HandlerFunction(f gin.HandlerFunc) gin.HandlerFunc{
    return func(cxt *gin.Context) {
        reqraceId := cxt.Request.Header.Get("trace-id")
        requid , _ := uuid.NewRandom()

        if reqTraceId == "" {
            c.Request.Header.Set("trace-id", requid.String())
        }

        f(c)
    }
}

最佳答案

可能值得阅读 context.Context,尤其是 this article其中有一节说:

At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests.

TL;DR - 传递上下文很好,但最好的方法是什么?

主要有两种模式

  1. 询问上下文给你一个记录器
  2. 为记录器提供上下文

上下文可以用来存储值:

context.WithValue(ctx, someKey, someValue)

这意味着我们可以:

somepackage.Log(ctx).Info("hello world")
// or
sompackage.Info(ctx, "hello world")

这两个示例 API 的实现可以与上下文交互以检索所需的值,而无需担心任何日志调用站点的 MDC 中的额外信息。

关于go - go微服务中如何给每条日志添加trace id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56343599/

相关文章:

ios - 如何在 iOS 应用程序中记录网络性能数据?

spring-cloud - Spring Cloud Stream Kafka - 最终一致性 - Kafka 是否自动重试未确认的消息(使用 autocommitoffset=false 时)

pointers - 如何在golang中正确打印出指针变量

xml - 编码 XML Go XMLName + xmlns

linux - 哪个日志文件或者如何找到该日志文件?

Python日志记录: debug messages logged to stderr even though handler level is INFO

java - 在微服务之间共享版本库有什么问题?

java - 微服务 - 多个服务副本之间的竞争条件

http - 使用 Golang 扫描网页

go - Beego c.ServeJson() 返回空