[Introduction]Jaeger链路追踪1/6 :demo|Go主题月

435 阅读1分钟

jaeger架构

jeager架构.png

Jeager-client :Go SDK jaeger-client-go 业务开发唯一需要关心的

Jeager-agent :负责将span信息发送至collector

Jeager-ui :负责展示的界面

Jeager-collector : 收集追踪最后进行存储

Data-store :负责对链路信息进行持久化存储

Jeager-query :从存储中检索信息并在UI中进行展示

部署

本地部署jaeger使用官网教程:

all-in-one需要依赖docker

$ docker run -d --name jaeger \
  -e COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
  -p 5775:5775/udp \
  -p 6831:6831/udp \
  -p 6832:6832/udp \
  -p 5778:5778 \
  -p 16686:16686 \
  -p 14268:14268 \
  -p 14250:14250 \
  -p 9411:9411 \
  jaegertracing/all-in-one:1.19

jaeger-demo

初始化jaeger配置:

采样率:有多大概率记录链路。一般设置为0.1/0.01等

如下所示为jaeger-go-client官网示例:

cfg := &config.Configuration{
    // 采样率
    Sampler: &config.SamplerConfig{
      Type:  "const",
      Param: 1,
    },
    // jeager agent config
    Reporter: &config.ReporterConfig{
      LogSpans:           true,
      LocalAgentHostPort: "127.0.0.1:6831",
    },
  }

单体应用请求

在单体应用中初始化jaeger tracer:

func InitTrancer(service string) (opentracing.Tracer, io.Closer) {
  cfg := &config.Configuration{
    // 采样率
    Sampler: &config.SamplerConfig{
      Type:  "const",
      Param: 1,
    },
    // jeager agent config
    Reporter: &config.ReporterConfig{
      LogSpans:           true,
      LocalAgentHostPort: "127.0.0.1:6831",
    },
  }
  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
}

按照官网教程即可进行链路追踪

http请求拦截器

在web开发中,比较常见的是对一个完整的http请求进行链路追踪,每一个http请求对应一个root-span,在拦截器中使用全局tracer记录:

// MiddlewareServerTracing is a serer middleware that enables tracing feature using standards of OpenTracing.
func Middleware(r *http.Request) {
	// get global tracer
        tracer := opentracing.GlobalTracer()

        // start root span
        span := tracer.StartSpan(r.URL.String())

        // root ctx
        ctx := opentracing.ContextWithSpan(context.Background(), span)

        // Inject tracing context.
        inject(...)
        defer span.Finish()
	
	r.Middleware.Next()
}