NewTracingManager 创建追踪管理器
(config TracingConfig)
| 42 | |
| 43 | // NewTracingManager 创建追踪管理器 |
| 44 | func NewTracingManager(config TracingConfig) (*TracingManager, error) { |
| 45 | if !config.Enabled { |
| 46 | return &TracingManager{config: config}, nil |
| 47 | } |
| 48 | |
| 49 | // 设置默认值 |
| 50 | if config.ServiceName == "" { |
| 51 | config.ServiceName = "aster" |
| 52 | } |
| 53 | if config.ServiceVersion == "" { |
| 54 | config.ServiceVersion = aster.Version |
| 55 | } |
| 56 | if config.Environment == "" { |
| 57 | config.Environment = "development" |
| 58 | } |
| 59 | if config.OTLPEndpoint == "" { |
| 60 | config.OTLPEndpoint = "localhost:4318" |
| 61 | } |
| 62 | if config.SamplingRate == 0 { |
| 63 | config.SamplingRate = 1.0 // 默认全采样 |
| 64 | } |
| 65 | |
| 66 | // 创建 OTLP HTTP exporter |
| 67 | opts := []otlptracehttp.Option{ |
| 68 | otlptracehttp.WithEndpoint(config.OTLPEndpoint), |
| 69 | } |
| 70 | if config.OTLPInsecure { |
| 71 | opts = append(opts, otlptracehttp.WithInsecure()) |
| 72 | } |
| 73 | |
| 74 | exporter, err := otlptracehttp.New(context.Background(), opts...) |
| 75 | if err != nil { |
| 76 | return nil, fmt.Errorf("failed to create OTLP exporter: %w", err) |
| 77 | } |
| 78 | |
| 79 | // 创建 Resource |
| 80 | res, err := resource.New( |
| 81 | context.Background(), |
| 82 | resource.WithAttributes( |
| 83 | semconv.ServiceNameKey.String(config.ServiceName), |
| 84 | semconv.ServiceVersionKey.String(config.ServiceVersion), |
| 85 | semconv.DeploymentEnvironmentKey.String(config.Environment), |
| 86 | ), |
| 87 | ) |
| 88 | if err != nil { |
| 89 | return nil, fmt.Errorf("failed to create resource: %w", err) |
| 90 | } |
| 91 | |
| 92 | // 创建 TracerProvider |
| 93 | provider := sdktrace.NewTracerProvider( |
| 94 | sdktrace.WithBatcher(exporter), |
| 95 | sdktrace.WithResource(res), |
| 96 | sdktrace.WithSampler(sdktrace.TraceIDRatioBased(config.SamplingRate)), |
| 97 | ) |
| 98 | |
| 99 | // 设置全局 TracerProvider |
| 100 | otel.SetTracerProvider(provider) |
| 101 |
no test coverage detected