使用jaeger作为作为链路追踪中间件
访问http://localhost:16686/查看jaeger ui
主要通过context传递trace id
- 配置全局的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
}
- 配置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{})
- 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))
- 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(),
),
}