golang 接入鏈路追蹤(opentracing)

huwlsc發表於2021-09-16

前言

本文主要講述 golang 如何接入開放式鏈路追蹤(opentracing)。

OpenTracing-Go-Plugins 介紹

opentracing-go-plugins是一個opentracing-go外掛庫。 該外掛庫支援 net/http、grpc、gin、goredis、gorm 等。

如何接入

引入包

go get -u github.com/yuewokeji/opentracing-go-plugins

初始化 tracer

我們以jaeger為例,先建立 tracer 例項,再呼叫方法opentracing.GlobalTracer()設定一個全域性的 tracer

package main

import (
    "github.com/opentracing/opentracing-go"
    "github.com/uber/jaeger-client-go"
    "github.com/uber/jaeger-client-go/transport"
    "io"
)

func initJaeger(service, url string) (opentracing.Tracer, io.Closer) {
    sender := transport.NewHTTPTransport(url)
    reporter := jaeger.NewRemoteReporter(sender, jaeger.ReporterOptions.Logger(jaeger.StdLogger))

    // samples 100% of traces
    tracer, closer := jaeger.NewTracer(service, jaeger.NewConstSampler(true), reporter)
    return tracer, closer
}

func initGlobalTracer() io.Closer {
    // the closer can be used in shutdown hooks
    tracer, closer := initJaeger("hello-world", "https://your-reporter-url")

    opentracing.SetGlobalTracer(tracer)
    return closer
}

gin 接入

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/yuewokeji/opentracing-go-plugins/module/otgin"
)

func main() {
    server := gin.New()
    server.Use(otgin.NewMiddleware(server))

    //do something
}

net/http 客戶端接入

package main

import (
    "github.com/yuewokeji/opentracing-go-plugins/module/othttp"
    "net/http"
    "strings"
)

func main() {
    client := othttp.WrapClient(&http.Client{})
    req, err := http.NewRequest("GET", "https://github.com", strings.NewReader(""))
    if err != nil {
        panic(err)
    }

    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    // do something
}

是不是非常簡單!!!

更多原創文章乾貨分享,請關注公眾號
  • golang 接入鏈路追蹤(opentracing)
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章