Skip to content

Latest commit

 

History

History
97 lines (80 loc) · 2.1 KB

链路追踪.md

File metadata and controls

97 lines (80 loc) · 2.1 KB

链路追踪

使用jaeger作为作为链路追踪中间件

访问http://localhost:16686/查看jaeger ui

配置示例

主要通过context传递trace id

  1. 配置全局的trace provider
package main

// Set global trace provider
func setTracerProvider(url string) error {
	// Create the Jaeger exporter
	exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		return err
	}
	tp := tracesdk.NewTracerProvider(
		// Set the sampling rate based on the parent span to 100%
		tracesdk.WithSampler(tracesdk.ParentBased(tracesdk.TraceIDRatioBased(1.0))),
		// Always be sure to batch in production.
		tracesdk.WithBatcher(exp),
		// Record information about this application in an Resource.
		tracesdk.WithResource(resource.NewSchemaless(
			semconv.ServiceNameKey.String(Name),
			attribute.String("env", "dev"),
		)),
	)
	otel.SetTracerProvider(tp)
	return nil
}
  1. 配置redis otel tracing
package data
import (
    "github.com/go-redis/redis/extra/redisotel"
)

rdb := redis.NewClient(&redis.Options{
    Addr:         c.Redis.Addr,
    DB:           int(c.Redis.Db),
    DialTimeout:  c.Redis.DialTimeout.AsDuration(),
    WriteTimeout: c.Redis.WriteTimeout.AsDuration(),
    ReadTimeout:  c.Redis.ReadTimeout.AsDuration(),
})
rdb.AddHook(redisotel.TracingHook{})
  1. ent配置otel tracing
drv, err := sql.Open(
    c.Database.Driver,
    c.Database.Source,
)

sqlDrv := dialect.DebugWithContext(drv, func(ctx context.Context, i ...interface{}) {
    log.WithContext(ctx).Info(i...)
    tracer := otel.Tracer("ent.")
    kind := trace.SpanKindServer
    _, span := tracer.Start(ctx,
        "Query",
        trace.WithAttributes(
            attribute.String("sql", fmt.Sprint(i...)),
        ),
        trace.WithSpanKind(kind),
    )
    span.End()
})
client := ent.NewClient(ent.Driver(sqlDrv))
  1. http,grpc trace middleware配置
package server

import (
	"github.com/go-kratos/kratos/v2/middleware/tracing"
)

var opts = []http.ServerOption{
    http.Middleware(
        recovery.Recovery(),
        validate.Validator(),
        tracing.Server(),
    ),
}