1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| type Tracing struct { opentracing.Tracer }
func NewTracing() (*Tracing, func(), error) { var ( err error closer io.Closer cfg *config.Configuration tracer opentracing.Tracer ) cfg = &config.Configuration{ Sampler: &config.SamplerConfig{ Type: "const", Param: 1, }, Reporter: &config.ReporterConfig{ LogSpans: true, LocalAgentHostPort: "192.168.165.21:6831", }, } tracer, closer, err = cfg.New( "test-tracing", config.Logger(jaeger.StdLogger), ) if err != nil { log.Fatalf("ERROR: cannot init Jaeger: %v", err) } closeFunc := func() { _ = closer.Close() } opentracing.SetGlobalTracer(tracer) tracing := &Tracing{ Tracer: tracer, } return tracing, closeFunc, err } ````
3. 使用, 一般的 gateway/webhttp 做为追踪的起点, 跟据客户端请求traceid, 服务端接收设置tag标记, 使用gin测试
```golang
func main () { g := gin.New() g.GET("/login", func(ctx *gin.Context) { option := opentracing.Tag{Key: "traceId", Value: ctx.GetHeader("traceId")} span, childctx := opentracing.StartSpanFromContext(ctx, "login", option) // 设置tag defer span.Finish() span.LogKV("loginRequest", ctx.Request.UserAgent()) selectdb := func() { dbspan, _ := opentracing.StartSpanFromContext(childctx, "selectFromDb") // 从父span派生child span defer dbspan.Finish() dbspan.LogKV("selectFromDb", "id:100") } selectdb() c.JSON(200, gin.H({"message": "ok"})) }) g.Run(":8080") }
|