traces.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package opentelemetry
  2. import (
  3. "context"
  4. extConfig "go-admin/config"
  5. "go.opentelemetry.io/otel"
  6. "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
  7. stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
  8. "go.opentelemetry.io/otel/propagation"
  9. "go.opentelemetry.io/otel/sdk/resource"
  10. sdktrace "go.opentelemetry.io/otel/sdk/trace"
  11. )
  12. func initTracer(res *resource.Resource) (*sdktrace.TracerProvider, error) {
  13. otelConfig := extConfig.ExtConfig.Otel
  14. endpoint := otelConfig.Common.Endpoint
  15. exporter := new(sdktrace.SpanExporter)
  16. var err error
  17. if endpoint == "" {
  18. *exporter, err = stdout.New(stdout.WithPrettyPrint())
  19. } else {
  20. *exporter, err = otlptracehttp.New(context.TODO(), otlptracehttp.WithEndpoint(endpoint), otlptracehttp.WithInsecure())
  21. }
  22. if err != nil {
  23. return nil, err
  24. }
  25. tp := sdktrace.NewTracerProvider(
  26. sdktrace.WithResource(res),
  27. sdktrace.WithSampler(sdktrace.AlwaysSample()),
  28. sdktrace.WithBatcher(*exporter),
  29. )
  30. otel.SetTracerProvider(tp)
  31. otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
  32. return tp, nil
  33. }