golang学习笔记(二):链路追踪

自定义http连接的服务端

package server

import (
	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	"net/http"
)

type MyServer struct {
	Server *http.Server
}

func GetServer() *MyServer {
	gin.SetMode(gin.ReleaseMode)
	engine := gin.New()
	s := &http.Server{
		Handler: engine,
	}
	return &MyServer{
		Server: s,
	}
}

func (s *MyServer) GetEngine() *gin.Engine {
	return s.Server.Handler.(*gin.Engine)
}

func (s *MyServer) Start(addr string) error {
	e := s.GetEngine()
	err2 := e.Run(addr)
	if err2 != nil {
		return err2
	}
	err := s.Server.ListenAndServe()
	if err != nil {
		return err
	}
	return nil
}

func (s *MyServer) EnableTracing() {
	s.GetEngine().Use(otelgin.Middleware("go20230923"))
}

初始化链路追踪

package tracing

import (
	"context"
	"fmt"
	"go.opentelemetry.io/contrib/propagators/b3"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
)

var tracer = otel.Tracer("go20230923")

func InitStdoutProvider(serviceName string) (func(ctx context.Context) error, error) {
	tracer = otel.Tracer(serviceName)
	// stdout as exporter
	exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
	if err != nil {
		return nil, err
	}
	tp := trace.NewTracerProvider(
		trace.WithSampler(trace.AlwaysSample()),
		trace.WithBatcher(exporter),
	)
	otel.SetTracerProvider(tp)

	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
	return tp.Shutdown, nil
}

注册路由

package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/trace"
	"go20230923/pkg/server"
	"log"
	"net/http"
)

func InitRouter(s *server.MyServer) {
	engine := s.GetEngine()
	group := engine.Group("/v1")
	group.GET("/hello", Hello)
	group.GET("/world", World)
}

func Hello(c *gin.Context) {
	if trace.SpanFromContext(c.Request.Context()).SpanContext().IsValid() {
		spanCtx := trace.SpanFromContext(c.Request.Context()).SpanContext()
		traceId := spanCtx.TraceID()
		spanId := spanCtx.SpanID()
		fmt.Printf("traceId : %s\n", traceId)
		fmt.Printf("spanId : %s\n", spanId)
	}
	fmt.Println("hello world")
	request, err := http.NewRequestWithContext(c.Request.Context(), "GET", "http://localhost:8080/v1/world", nil)
	if err != nil {
		log.Fatal(err)
	}
	client := http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
	client.Do(request)
}

func World(c *gin.Context) {
	if trace.SpanFromContext(c.Request.Context()).SpanContext().IsValid() {
		spanCtx := trace.SpanFromContext(c.Request.Context()).SpanContext()
		traceId := spanCtx.TraceID()
		spanId := spanCtx.SpanID()
		fmt.Printf("traceId : %s\n", traceId)
		fmt.Printf("spanId : %s\n", spanId)
	}
	fmt.Println("hello world")
}

启动入口

package main

import (
	"fmt"
	"go20230923/pkg/server"
	"go20230923/pkg/tracing"
	"go20230923/router"
)

func main() {
	s := server.GetServer()
	s.EnableTracing()
	tracing.InitStdoutProvider("go20230923")
	router.InitRouter(s)
	err := s.Start(":8080")
	if err != nil {
		fmt.Println(err)
	}
}

GET http://localhost:8080/v1/hello 输出:

traceId : 302c3e67a16bd20ce35b9220a4297d08
spanId : f80dd7189261ed84
hello world
traceId : 302c3e67a16bd20ce35b9220a4297d08
spanId : 7826014d750cf1c5
hello world
{

        "Name": "/v1/world",
        "SpanContext": {
                "TraceID": "302c3e67a16bd20ce35b9220a4297d08",
                "SpanID": "7826014d750cf1c5",
                "TraceFlags": "01",
                "TraceState": "",
                "Remote": false
        },
        "Parent": {
                "TraceID": "302c3e67a16bd20ce35b9220a4297d08",
                "SpanID": "aaa69798fdc0e90c",
                "TraceFlags": "01",
                "TraceState": "",
                "Remote": true
        },
        "SpanKind": 2,
        "StartTime": "2023-09-29T11:32:41.5265746+08:00",
        "EndTime": "2023-09-29T11:32:41.5271363+08:00",
        "Attributes": [
                {
                        "Key": "http.method",
                        "Value": {
                                "Type": "STRING",
                                "Value": "GET"
                        }
                },
                {
                        "Key": "http.scheme",
                        "Value": {
                                "Type": "STRING",
                                "Value": "http"
                        }
                },
                {
                        "Key": "http.flavor",
                        "Value": {
                                "Type": "STRING",
                                "Value": "1.1"
                        }
                },
                {
                        "Key": "net.host.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "go20230923"
                        }
                },
                {
                        "Key": "net.host.port",
                        "Value": {
                                "Type": "INT64",
                                "Value": 8080
                        }
                },
                {
                        "Key": "net.sock.peer.addr",
                        "Value": {
                                "Type": "STRING",
                                "Value": "::1"
                        }
                },
                {
                        "Key": "net.sock.peer.port",
                        "Value": {
                                "Type": "INT64",
                                "Value": 62471
                        }
                },
                {
                        "Key": "http.user_agent",
                        "Value": {
                                "Type": "STRING",
                                "Value": "Go-http-client/1.1"
                        }
                },
                {
                        "Key": "http.route",
                        "Value": {
                                "Type": "STRING",
                                "Value": "/v1/world"
                        }
                },
                {
                        "Key": "http.status_code",
                        "Value": {
                                "Type": "INT64",
                                "Value": 200
                        }
                }
        ],
        "Events": null,
        "Links": null,
        "Status": {
                "Code": "Unset",
                "Description": ""
        },
        "DroppedAttributes": 0,
        "DroppedEvents": 0,
        "DroppedLinks": 0,
        "ChildSpanCount": 0,
        "Resource": [
                {
                        "Key": "service.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "unknown_service:___go_build_go20230923.exe"
                        }
                },
                {
                        "Key": "telemetry.sdk.language",
                        "Value": {
                                "Type": "STRING",
                                "Value": "go"
                        }
                },
                {
                        "Key": "telemetry.sdk.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "opentelemetry"
                        }
                },
                {
                        "Key": "telemetry.sdk.version",
                        "Value": {
                                "Type": "STRING",
                                "Value": "1.18.0"
                        }
                }
        ],
        "InstrumentationLibrary": {
                "Name": "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin",
                "Version": "0.44.0",
                "SchemaURL": ""
        }
}
{
        "Name": "/v1/hello",
        "SpanContext": {
                "TraceID": "302c3e67a16bd20ce35b9220a4297d08",
                "SpanID": "f80dd7189261ed84",
                "TraceFlags": "01",
                "TraceState": "",
                "Remote": false
        },
        "Parent": {
                "TraceID": "00000000000000000000000000000000",
                "SpanID": "0000000000000000",
                "TraceFlags": "00",
                "TraceState": "",
                "Remote": false
        },
        "SpanKind": 2,
        "StartTime": "2023-09-29T11:32:41.5252493+08:00",
        "EndTime": "2023-09-29T11:32:41.5271363+08:00",
        "Attributes": [
                {
                        "Key": "http.method",
                        "Value": {
                                "Type": "STRING",
                                "Value": "GET"
                        }
                },
                {
                        "Key": "http.scheme",
                        "Value": {
                                "Type": "STRING",
                                "Value": "http"
                        }
                },
                {
                        "Key": "http.flavor",
                        "Value": {
                                "Type": "STRING",
                                "Value": "1.1"
                        }
                },
                {
                        "Key": "net.host.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "go20230923"
                        }
                },
                {
                        "Key": "net.host.port",
                        "Value": {
                                "Type": "INT64",
                                "Value": 8080
                        }
                },
                {
                        "Key": "net.sock.peer.addr",
                        "Value": {
                                "Type": "STRING",
                                "Value": "::1"
                        }
                },
                {
                        "Key": "net.sock.peer.port",
                        "Value": {
                                "Type": "INT64",
                                "Value": 64585
                        }
                },
                {
                        "Key": "http.user_agent",
                        "Value": {
                                "Type": "STRING",
                                "Value": "PostmanRuntime/7.28.0"
                        }
                },
                {
                        "Key": "http.route",
                        "Value": {
                                "Type": "STRING",
                                "Value": "/v1/hello"
                        }
                },
                {
                        "Key": "http.status_code",
                        "Value": {
                                "Type": "INT64",
                                "Value": 200
                        }
                }
        ],
        "Events": null,
        "Links": null,
        "Status": {
                "Code": "Unset",
                "Description": ""
        },
        "DroppedAttributes": 0,
        "DroppedEvents": 0,
        "DroppedLinks": 0,
        "ChildSpanCount": 1,
        "Resource": [
                {
                        "Key": "service.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "unknown_service:___go_build_go20230923.exe"
                        }
                },
                {
                        "Key": "telemetry.sdk.language",
                        "Value": {
                                "Type": "STRING",
                                "Value": "go"
                        }
                },
                {
                        "Key": "telemetry.sdk.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "opentelemetry"
                        }
                },
                {
                        "Key": "telemetry.sdk.version",
                        "Value": {
                                "Type": "STRING",
                                "Value": "1.18.0"
                        }
                }
        ],
        "InstrumentationLibrary": {
                "Name": "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin",
                "Version": "0.44.0",
                "SchemaURL": ""
        }
}
参考

Go语言 如何获取有关 *gin.Context.Request.Context()的详细信息
golang 使用 OpenTelemetry 实现跨服务全链路追踪
github go-moda项目

你可能感兴趣的:(golang)