docker run -d -p 5775:5775/udp -p 16686:16686 jaegertracing/all-in-one:latest
//初始化jaeger
func initJaeger(service string) (opentracing.Tracer, io.Closer) {
cfg := &config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
},
}
tracer, closer, err := cfg.New(service, config.Logger(jaeger.StdLogger))
if err != nil {
panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err))
}
return tracer, closer
}
//初始化
tracer, closer := initJaeger("hello-world")
defer closer.Close()
//开始一个span
span := tracer.StartSpan("say-hello")
span.SetTag("hello-to", helloTo)
defer span.Finish()
//向下一个span传递
func test(rootSpan opentracing.Span, helloStr string) {
span := rootSpan.Tracer().StartSpan("test",opentracing.ChildOf(rootSpan.Context()))
defer span.Finish()
println(helloStr)
span.LogKV("event", "test")
}
//初始化
tracer, closer := initJaeger("hello-world")
defer closer.Close()
opentracing.SetGlobalTracer(tracer)//这个必须设置
//开始一个span
span := tracer.StartSpan("say-hello")
span.SetTag("hello-to", helloTo)
defer span.Finish()
//使用context进行span的传递
ctx := context.Background()
ctx = opentracing.ContextWithSpan(ctx,span)
test(ctx,"test")
//test函数
func test(ctx context.Context, helloStr string) {
//取出根span
span,_ := opentracing.StartSpanFromContext(ctx,"test")
defer span.Finish()
println(helloStr)
span.LogKV("event", "test")
//如果还需要向下传递,重新设置span的上下文
ctx = opentracing.ContextWithSpan(ctx,span)
test2(ctx,"test2")
}
OpenTracing API在Tracer界面中提供了两个功能来实现: Inject(spanContext, format, carrier)以及Extract(format, carrier)
该format参数指的是OpenTracing API定义的三种标准编码之一:
TextMap:其中span上下文被编码为字符串键值对的集合,
Binary:其中span上下文被编码为不透明的字节数组,
HTTPHeaders:类似于TextMap,除了密钥必须安全用作HTTP头。
这carrier是对底层RPC框架的抽象。例如,TextMap格式的载体是一个允许跟踪器通过Set(key, value)函数写入键值对的接口,而二进制格式的载体只是一个io.Writer
//调用端
import (
"github.com/opentracing/opentracing-go/ext"
)
ext.SpanKindRPCClient.Set(span)
ext.HTTPUrl.Set(span, url)
ext.HTTPMethod.Set(span, "GET")
span.Tracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header),
)
spanCtx, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))
span := tracer.StartSpan("format", ext.RPCServerOption(spanCtx))
defer span.Finish()
//父
span.SetBaggageItem("greeting", greeting) //设置
//子
greeting := span.BaggageItem("greeting") //获取