package trace import ( "context" "fmt" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/jaeger" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" "net/url" "sync" ) const ( kindJaeger = "jaeger" ) var ( lock sync.Mutex tp *sdktrace.TracerProvider ) func StartAgent(c Config) { lock.Lock() defer lock.Unlock() if err := startAgent(c); err != nil { return } } func StopAgent() { _ = tp.Shutdown(context.Background()) } func createExporter(c Config) (sdktrace.SpanExporter, error) { //switch c.Batcher { //case kindJaeger: u, _ := url.Parse(c.Endpoint) if u.Scheme == "udp" { return jaeger.New(jaeger.WithAgentEndpoint(jaeger.WithAgentHost(u.Host), jaeger.WithAgentPort(u.Port()))) } return jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(u.Host))) //} } func startAgent(c Config) error { opts := []sdktrace.TracerProviderOption{ sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(c.Sampler))), sdktrace.WithResource(resource.NewSchemaless(semconv.ServiceNameKey.String(c.Name))), } if len(c.Endpoint) > 0 { exp, err := createExporter(c) if err != nil { return err } opts = append(opts, sdktrace.WithBatcher(exp)) } tp = sdktrace.NewTracerProvider(opts...) otel.SetTracerProvider(tp) otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) { fmt.Println("[otel]", err) })) return nil }