在 Azure SDK for Java 中配置跟踪

本文概述如何配置 Azure SDK for Java 以集成跟踪功能。

可以通过使用和配置 OpenTelemetry SDK 或使用与 OpenTelemetry 兼容的代理在 Azure 客户端库中启用跟踪。 OpenTelemetry 是一种常用的开源可观测性框架,用于为云原生软件生成、捕获和收集遥测数据。

与跟踪有关的关键概念有两个:“范围”和“跟踪”。 范围表示跟踪中的单个操作。 范围可以表示 HTTP 请求、远程过程调用 (RPC)、数据库查询甚至是代码所采用的路径。 跟踪是显示整个系统的工作路径的范围树。 可以通过称为 TraceID 的唯一 16 字节序列来区分跟踪。 有关这些概念及其与 OpenTelemetry 的关系的详细信息,请参阅 OpenTelemetry 文档

使用 Azure Monitor Java 代理进行 Azure SDK 跟踪

通过使用 Azure Monitor Java 进程内代理,可以启用应用程序监视,而无需进行任何代码更改。 有关详细信息,请参阅适用于 Java 应用程序的 Azure Monitor 基于 OpenTelemetry 的自动检测。 从代理版本 3.2 开始,默认启用 Azure SDK 支持。

使用 OpenTelemetry 代理跟踪 Azure SDK 调用

如果使用 OpenTelemetry Java 代理,则从版本 1.12.0 开始,Azure SDK 检测已开箱即用。

有关如何配置导出程序、添加手动检测或扩充遥测的更多详细信息,请参阅 适用于 Java 的 OpenTelemetry Instrumentation。

注意

OpenTelemetry 代理项目稳定,但不提供无线遥测稳定性保证,这可能会导致 Azure SDK 生成的跨度名称和属性名称,如果在更新代理时可能会随时间变化。 有关详细信息,请参阅 兼容性要求

使用 OpenTelemetry SDK 手动检测应用程序(预览版)

如果直接使用 OpenTelemetry SDK,请确保为所选后端配置 SDK 和导出程序。 有关详细信息,请参阅 OpenTelemetry 文档

若要启用 Azure SDK 跟踪,请将最新的 com.azure:azure-core-tracing-opentelemetry 包添加到应用程序。 例如,在 Maven 中,将以下条目添加到 pom.xml 文件中:

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core-tracing-opentelemetry</artifactId>
</dependency>

如果现在运行应用程序,则应在后端获取 Azure SDK 范围。 但是,使用异步调用时,Azure SDK 与应用程序范围之间的关联可能会中断。

默认情况下,Azure SDK 使用 io.opentelemetry.context.Context.current()OpenTelemetry 隐式传播为新范围的父级。 在异步调用中,隐式上下文传播中断。 OpenTelemetry 代理通过帮助上下文传播来解决此问题,但 OpenTelemetry SDK 没有此类功能。

显式传递跟踪上下文

Azure SDK 允许在密钥下trace-context显式com.azure.core.util.Context传递跟踪上下文。 提供显式跟踪上下文时,Azure SDK 使用它而不是隐式跟踪上下文,从而在应用程序和 Azure SDK 跨度之间实现关联。

在以下示例中,手动跟踪传入的 Web 请求时,应用程序配置客户端库会在此请求的范围内异步调用。

Span span = TRACER.spanBuilder("incoming request").startSpan();
io.opentelemetry.context.Context traceContext = io.opentelemetry.context.Context.root().with(span);

// Put the incoming-request span (wrapped into the OpenTelemetry Context) into the Azure SDK Context
// and pass it over to the Application Configuration call.
appConfigClient.setConfigurationSettingWithResponse(settings, true, new com.azure.core.util.Context("trace-context", traceContext));

// You could also pass the context using the reactor `contextWrite` method under the same `trace-context` key.
appConfigAsyncClient.setConfigurationSettingWithResponse(settings)
   .contextWrite(reactor.util.context.Context.of("trace-context", traceContext))

//...

Azure SDK 跟踪约定

若要了解 SDK 发出的跨度和属性,请参阅 Azure SDK 语义约定规范。 Azure SDK(和 OpenTelemetry)语义约定不稳定,将来可能会更改。

后续步骤

现在你已熟悉 Azure SDK for Java 中的核心跨领域功能,请参阅使用 Java 和 Azure 标识进行 Azure 身份验证,了解如何创建安全的应用程序。