OpenTelemetryConfig
类,代码如下所示:
// src/main/java/com/youdianzhishi/orderservice/config/OpenTelemetryConfig.javapackage com.youdianzhishi.orderservice.config;import io.opentelemetry.api.OpenTelemetry;import io.opentelemetry.api.common.Attributes;import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;import io.opentelemetry.sdk.OpenTelemetrySdk;import io.opentelemetry.sdk.resources.Resource;import io.opentelemetry.sdk.trace.SdkTracerProvider;import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;@Configuration@Order(2)public class OpenTelemetryConfig { @Bean public OpenTelemetry openTelemetry() { GlobalOpenTelemetry.resetForTest(); // 初始化之前先重置 GlobalOpenTelemetry // 从环境变量中获取 OTLP Exporter 的地址 String exporterEndpointFromEnv = System.getenv("OTLP_EXPORTER_ENDPOINT"); String exporterEndpoint = exporterEndpointFromEnv != null ? exporterEndpointFromEnv : "http://otel-collector:4317"; String serviceNameFromEnv = System.getenv("SERVICE_NAME"); String serviceName = serviceNameFromEnv != null ? serviceNameFromEnv : "order-service"; // 初始化 OTLP Exporter OtlpGrpcSpanExporter exporter = OtlpGrpcSpanExporter.builder() .setEndpoint(exporterEndpoint) .build(); Resource resource = Resource.getDefault() .merge(Resource.create(Attributes.of( ResourceAttributes.SERVICE_NAME, serviceName, ResourceAttributes.TELEMETRY_SDK_LANGUAGE, "java"))); // 初始化 TracerProvider SdkTracerProvider tracerProvider = SdkTracerProvider.builder() .addSpanProcessor(SimpleSpanProcessor.create(exporter)) .setResource(resource) .build(); // 初始化 ContextPropagators,这里我们配置包含 W3C Trace Context 和 W3C Baggage ContextPropagators propagators = ContextPropagators.create( TextMapPropagator.composite( W3CTraceContextPropagator.getInstance(), W3CBaggagePropagator.getInstance())); // 初始化并返回 OpenTelemetry SDK return OpenTelemetrySdk.builder() .setPropagators(propagators) .setTracerProvider(tracerProvider) .buildAndRegisterGlobal(); } @Bean public Tracer tracer() { return openTelemetry().getTracer(OrderserviceApplication.class.getName()); }}
推荐阅读
- 通过诗经楚辞取的公司名字
- 动量定理的应用 动量定理的应用视频讲解
- 深入浅出、玩转Java多线程
- 揭秘十个必知的 JavaScript 3D 库,打造顶级3D炫酷效果!
- 图灵测试已死!ChatGPT通过人类考试也不算,超强AI评估新秀「逻辑谜题」
- 王者荣耀的段位排行榜是通过Redis实现的?
- 我不再写Javascript了
- Java 单元测试及常用语句
- 构建高效的Java网络应用,体验秒级响应
- 谷歌推出 AlloyDB AI,帮助开发者创建生成式 AI 应用