带 context 的追踪
最后更新于:2022-04-02 02:57:41
[TOC]
## 带 context 的追踪
![7A036E37-62F8-4C68-8D68-487E78A76619.png](http://yanxuan.nosdn.127.net/23889f64ede3e0b3ff91055b493dff25.png)
';
详情
``` package main import ( "context" "fmt" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/log" "github.com/uber/jaeger-client-go/config" "io" ) func Init(service string) (opentracing.Tracer, io.Closer) { cfg := &config.Configuration{ ServiceName: service, Sampler: &config.SamplerConfig{ Type: "const", //全部采样 Param: 1, //1 开启全部采样,0 关闭全部采样,可通过 环境变量 JAEGER_SAMPLER_PARAM 控制 }, Reporter: &config.ReporterConfig{ LogSpans: true, //LocalAgentHostPort: "127.0.0.1:6831", }, } tracer, closer, err := cfg.NewTracer( )//log.StdLogger 只要实现日志接口即可 if err != nil { panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err)) } return tracer, closer } func main() { tracer, closer := Init("hello-world33") defer closer.Close() opentracing.SetGlobalTracer(tracer) helloTo := "helo" span := tracer.StartSpan("say-hello") span.SetTag("hello-to", helloTo) defer span.Finish() ctx := opentracing.ContextWithSpan(context.Background(), span) ctx2 := formatString(ctx, helloTo) printHello(ctx2,"word") } func formatString(ctx context.Context, helloTo string) context.Context { span, ctx := opentracing.StartSpanFromContext(ctx, "formatString") defer span.Finish() helloStr := fmt.Sprintf("Hello, %s!", helloTo) span.LogFields( log.String("event", "string-format"), log.String("value", helloStr), ) return ctx } func printHello(ctx context.Context, helloStr string) { span, _ := opentracing.StartSpanFromContext(ctx, "printHello") defer span.Finish() println(helloStr) span.LogKV("event", "println") } ```![7A036E37-62F8-4C68-8D68-487E78A76619.png](http://yanxuan.nosdn.127.net/23889f64ede3e0b3ff91055b493dff25.png)