current position:Home>Small example of distributed link tracing opentracing-go jaeger

Small example of distributed link tracing opentracing-go jaeger

2022-08-06 09:24:05kankan231

opentracingis a set of distributed link tracking specifications,jaeger(Uber开源)is the normgo语言实现,Distributed link tracing is mainly used in complex distributed systems(如微服务)Call chain tracing and performance analysis

jaeger提供了docker的all-in-one包,里面包含了agent,collector,query,ui等组件,安装:

docker run -d  -p 5775:5775/udp    -p 16686:16686    -p 6831:6831/udp   -p 6832:6832/udp   -p 5778:5778   -p 14268:14268    jaegertracing/all-in-one:latest

启动后可在http://ip:16686View tracked data

客户端代码:

package main

import (
	//	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"time"

	"github.com/uber/jaeger-client-go"

	"github.com/opentracing/opentracing-go"
	//	"github.com/opentracing/opentracing-go/log"
	"github.com/uber/jaeger-client-go/config"
)

const (
	URL      = "http://localhost:8080"
	LIST_API = "/getList"
)

var (
	flag = make(chan bool)
)

func TraceInit(serviceName string, samplerType string, samplerParam float64) (opentracing.Tracer, io.Closer) {
	cfg := &config.Configuration{
		ServiceName: serviceName,
		Sampler: &config.SamplerConfig{
			Type:  samplerType,
			Param: samplerParam,
		},
		Reporter: &config.ReporterConfig{
			LocalAgentHostPort: "127.0.0.1:6831", //jaeger agent address
			LogSpans:           true,
		},
	}

	tracer, closer, err := cfg.NewTracer(config.Logger(jaeger.StdLogger))
	if err != nil {
		panic(fmt.Sprintf("Init failed: %v\n", err))
	}

	return tracer, closer
}

func sendRequest(req *http.Request) {
	go func(req *http.Request) {
		resp, err := http.DefaultClient.Do(req)

		if err != nil {
			fmt.Printf("Do send requst failed(%s)\n", err)
			return
		}

		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("ReadAll error(%s)\n", err)
			return
		}

		if resp.StatusCode != 200 {
			return
		}
		time.Sleep(time.Millisecond * 50)
		fmt.Printf("Response:%s\n", string(body))
		flag <- true
	}(req)
}

func main() {

	reqURL := URL + LIST_API

	tracer, closer := TraceInit("client-tracing", "const", 1)
	defer closer.Close()
	opentracing.SetGlobalTracer(tracer)
	span := tracer.StartSpan(fmt.Sprintf("%s trace", LIST_API))
	span.SetTag("请求url", reqURL) //span tag
	defer span.Finish()

	var err error

	req, err := http.NewRequest("GET", reqURL, nil)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	//将trace信息添加到http request header
	span.Tracer().Inject(
		span.Context(),
		opentracing.HTTPHeaders,
		opentracing.HTTPHeadersCarrier(req.Header),
	)
	fmt.Println(req.Header)
	sendRequest(req)

	<-flag
}

服务器端代码:

package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/uber/jaeger-client-go"

	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"github.com/uber/jaeger-client-go/config"
)

var (
	tracer opentracing.Tracer
)

func TraceInit(serviceName string, samplerType string, samplerParam float64) (opentracing.Tracer, io.Closer) {
	cfg := &config.Configuration{
		ServiceName: serviceName,
		Sampler: &config.SamplerConfig{
			Type:  samplerType,
			Param: samplerParam,
		},
		Reporter: &config.ReporterConfig{
			LocalAgentHostPort: "127.0.0.1:6831",
			LogSpans:           true,
		},
	}

	tracer, closer, err := cfg.NewTracer(config.Logger(jaeger.StdLogger))
	if err != nil {
		panic(fmt.Sprintf("Init failed: %v\n", err))
	}

	return tracer, closer
}

func GetListProc(w http.ResponseWriter, req *http.Request) {

	//从http request header 中提取trace信息
	spanCtx, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
	span := tracer.StartSpan("GetListProc", ext.RPCServerOption(spanCtx))
	defer span.Finish()

	fmt.Println("Get request getList")
	respList := []string{"l1", "l2", "l3", "l4", "l5"}
	respString := strings.Join(respList, ",")

	time.Sleep(100 * time.Millisecond)

	fmt.Println(respString)
	io.WriteString(w, respString)
}

func main() {
	var closer io.Closer
	tracer, closer = TraceInit("Trace-Server", "const", 1)
	defer closer.Close()

	http.HandleFunc("/getList", GetListProc)

	http.ListenAndServe(":8080", nil)
}

运行结果

服务端:

go run .\main.go
2022/07/30 15:07:44 debug logging disabled
2022/07/30 15:07:44 Initializing logging reporter
2022/07/30 15:07:44 debug logging disabled
Get request getList
l1,l2,l3,l4,l5
2022/07/30 15:09:12 Reporting span 2be328063be80f70:2669e721d49e49a0:2be328063be80f70:1

客户端:

go run .\main.go        
2022/07/30 15:09:12 debug logging disabled
2022/07/30 15:09:12 Initializing logging reporter
2022/07/30 15:09:12 debug logging disabled
map[Uber-Trace-Id:[2be328063be80f70:2be328063be80f70:0000000000000000:1]]
Response:l1,l2,l3,l4,l5
2022/07/30 15:09:12 Reporting span 2be328063be80f70:2be328063be80f70:0000000000000000:1

在Jaeger UIView tracking data:

Each can be seen from the resultsspan的tagdata and time 

copyright notice
author[kankan231],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/218/202208060917043100.html

Random recommended