Go语言 如何获取有关 *gin.Context.Request.Context()的详细信息

new9mtju  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(385)

我试图使用otelgin来跟踪我的项目,它说where required. It is available from gin.Context.Request.Context(),所以我如何从gin.context中获得详细信息,看看它是否工作。
正式地,他们在初始化tracer provider时添加了一个stdout作为导出器:

func initTracer() (*sdktrace.TracerProvider, error) {
    // stdout as exporter
    exporter, err := stdout.New(stdout.WithPrettyPrint())
    if err != nil {
        return nil, err
    }
    tp := sdktrace.NewTracerProvider(
        sdktrace.WithSampler(sdktrace.AlwaysSample()),
        sdktrace.WithBatcher(exporter),
    )
    otel.SetTracerProvider(tp)
 
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
    return tp, nil
}

以下是命令行输出的一部分:

"Name": "/users/:id",
    "SpanContext": {
        "TraceID": "e7a43d30c0e507b4c59fd65dc3bc6d77",
        "SpanID": "636c22201c903573",
        "TraceFlags": "01",
        "TraceState": "",
        "Remote": false
    },
    "Parent": {
        "TraceID": "00000000000000000000000000000000",
        "SpanID": "0000000000000000",
        "TraceFlags": "00",
        "TraceState": "",
        "Remote": false
    },
    "SpanKind": 2,
    "StartTime": "2022-11-12T16:02:07.871843+08:00",
    "EndTime": "2022-11-12T16:02:07.871843+08:00",

但是有没有办法从gin.context中得到这个表单呢?或者我可以从gin.context中得到导出者的详细信息呢?我试着添加一个中间件来捕获它们,如下所示:

func TracerGetMiddleware(c *gin.Context) {
    //var tracer oteltrace.Tracer
    //tracerInterface, ok := c.Get("otel-go-contrib-tracer")
    //if ok {
    /// tracer, ok = tracerInterface.(oteltrace.Tracer)
    //}
    //tracer.Start(c, "test")
    fmt.Println(c.Request.Context())
}

但这是c.Request.Context()的输出

(type *http.contextKey, val <not Stringer>).WithValue(type *http.contextKey, val [::1]:8088).WithCancel.WithCancel.WithValue(type trace.traceContextKeyType, val <not Stringer>)
7uhlpewt

7uhlpewt1#

目前我明白了我最初想得到的答案,那就是在gin.context中得到traceID、SpanID等数据

import (
    "fmt"
    "github.com/gin-gonic/gin"
    oteltrace "go.opentelemetry.io/otel/trace"
)

func GetIDMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        if oteltrace.SpanFromContext(c.Request.Context()).SpanContext().IsValid() {
            TraceID := oteltrace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()
            SpanID := oteltrace.SpanFromContext(c.Request.Context()).SpanContext().SpanID().String()
            fmt.Println(TraceID)
            fmt.Println(SpanID)
        }
    }
}

我最初的想法是通过otelgin传递context中的trace信息,然后在gin的中间件中通过context捕获traceID等进行zap日志记录,但当时我不知道如何获取TraceID等信息,看到gin-contrib/zap库时找到了正确的方法。

相关问题