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

如何在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.

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真