Tracing

We use OpenTelemetry for distributed tracing.

Configuration

There are two methods for configuration WithTracerProvider() and WithPropagator().

WithTracerProvider

  1. func WithTracerProvider(provider trace.TracerProvider) Option {
  2. return func(opts *options) {
  3. opts.TracerProvider = provider
  4. }
  5. }

WithTracerProvider is for setting the provider, it accepts trace.TracerProvider

WithPropagator

  1. func WithPropagator(propagator propagation.TextMapPropagator) Option {
  2. return func(opts *options) {
  3. opts.Propagator = propagator
  4. }
  5. }

WithPropagator is for setting the text map propagator, it accepts propagation.TextMapPropagator

Usage

Tracing for Server

  1. package server
  2. func initTracer() func() {
  3. // create a jaeger pipeline
  4. flush, err := jaeger.InstallNewPipeline(
  5. jaeger.WithCollectorEndpoint("http://localhost:14268/api/traces"),
  6. jaeger.WithSDKOptions(
  7. sdktrace.WithSampler(sdktrace.AlwaysSample()),
  8. sdktrace.WithResource(resource.NewWithAttributes(
  9. semconv.ServiceNameKey.String("kratos-trace"),
  10. attribute.String("exporter", "jaeger"),
  11. attribute.Float64("float", 312.23),
  12. )),
  13. ),
  14. )
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. return flush
  19. }
  20. // NewGRPCServer new a gRPC server.
  21. func NewGRPCServer(c *conf.Server, executor *service.ExecutorService) *grpc.Server {
  22. flush := initTracer()
  23. defer flush()
  24. //tr := otel.Tracer("component-main")
  25. var opts = []grpc.ServerOption{
  26. grpc.Middleware(
  27. middleware.Chain(
  28. tracing.Server(tracing.WithTracerProvider(otel.GetTracerProvider())),
  29. ),
  30. ),
  31. }
  32. // ...
  33. }

Tracing for Client

  1. func initTracer() func() {
  2. // create a jaeger pipeline
  3. flush, err := jaeger.InstallNewPipeline(
  4. jaeger.WithCollectorEndpoint("http://localhost:14268/api/traces"),
  5. jaeger.WithSDKOptions(
  6. sdktrace.WithSampler(sdktrace.AlwaysSample()),
  7. sdktrace.WithResource(resource.NewWithAttributes(
  8. semconv.ServiceNameKey.String("kratos-trace"),
  9. attribute.String("exporter", "jaeger"),
  10. attribute.Float64("float", 312.23),
  11. )),
  12. ),
  13. )
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. return flush
  18. }
  19. func grpcCli() (*grpc.ClientConn, error) {
  20. return grpc.DialInsecure(
  21. context.Background(),
  22. grpc.WithMiddleware(
  23. tracing.Client(
  24. tracing.WithTracerProvider(
  25. otel.GetTracerProvider(),
  26. ),
  27. ),
  28. ),
  29. )
  30. }

References