doutao6330 2019-05-28 13:42
浏览 1343
已采纳

如何在Go Micro Service中为每个日志添加跟踪ID

I wanted to add trace id to logging done for each request to the micro service.I want this in similar as for springboot application we can set trace id in MDC and fetch it and use it while logging.

I have done some research and I found that MDC equivalent in go lang is context. So, I have set the trace id in my context. Now the problem is where ever I have to log with trace id ,I need to pass context to that function which is very ugly way. I am looking for a better solution for this problem.

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)
    }
}
  • 写回答

1条回答 默认 最新

  • doucai9270 2019-05-28 21:20
    关注

    It might be worth reading up on context.Context particularly this article which has a section that says:

    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 - it's fine to pass the context, but what's the best way?

    There's two main patterns

    1. Ask the context to give you a logger
    2. Give the logger the context

    Context can be used to store values:

    context.WithValue(ctx, someKey, someValue)
    

    This means we can either do:

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

    The implementation of these two sample APIs could interact with the context to retrieve the values required with out needing to worry about the extra information that would have been in MDC at any of the logging call sites.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?