在 Application Insights 中配置 OpenTelemetry

注意

对于.NET、Node.js和Python应用程序:

对于Java应用程序,请使用 Azure Monitor OpenTelemetry 发行版。

本指南介绍如何在 Azure Monitor Application Insights 中配置 OpenTelemetry (OTel)。 对于 .NET、Node.js和 Python,请使用 Microsoft OpenTelemetry 发行版。 对于Java,请使用 Azure Monitor OpenTelemetry 发行版及其现有的代理或本机映像集成。

首先,为你的编程语言启用 OpenTelemetry。

Microsoft OpenTelemetry 发行版包标识符和安装命令包括:

语言 Package 安装命令
Python microsoft-opentelemetry pip install microsoft-opentelemetry
Node.js @microsoft/opentelemetry npm install @microsoft/opentelemetry
.NET Microsoft.OpenTelemetry dotnet add package Microsoft.OpenTelemetry

不要同时初始化 Microsoft OpenTelemetry 发行版和 Azure Monitor OpenTelemetry 发行版。 Azure Monitor仍然是遥测目标;独立Azure Monitor导出程序保留其现有名称。

.NET示例使用Microsoft.OpenTelemetry和 OpenTelemetry 命名空间。 在应用程序库加载之前初始化 Node.js 插桩。 ESM 应用程序必须预加载 Microsoft OpenTelemetry 发行版加载程序。 除非示例在代码中设置连接字符串,否则请在启动应用程序之前设置APPLICATIONINSIGHTS_CONNECTION_STRING。

注意

有关 Azure 函数应用,请参阅 将 OpenTelemetry 与 Azure Functions 配合使用。

连接字符串

在 Application Insights 中,“Connection String” 定义了用于发送遥测数据的目标地点。

使用以下三种方法之一配置连接字符串:

  • 在UseMicrosoftOpenTelemetry()中配置Program.cs。

    // Import the Microsoft OpenTelemetry Distro and supporting APIs.
    using Microsoft.OpenTelemetry;
    
    // Create the application builder.
    var builder = WebApplication.CreateBuilder(args);
    
    // Configure the Microsoft OpenTelemetry Distro.
    builder.UseMicrosoftOpenTelemetry(options =>
    {
      options.Exporters = ExportTarget.AzureMonitor;
    
      // Set the connection string for Azure Monitor export.
      options.AzureMonitor.ConnectionString = "<ConnectionString>";
    });
    
    // Build the application with the configured telemetry services.
    var app = builder.Build();
    
    // Run the application and its telemetry providers.
    app.Run();
    
  • 设置环境变量。

    export APPLICATIONINSIGHTS_CONNECTION_STRING="<ConnectionString>"
    
  • 将以下部分添加到 appsettings.json其中,然后在初始化发行版时读取它。

        {
            "AzureMonitor": {
                "ConnectionString": "<ConnectionString>"
            }
        }
    
    // Import the Microsoft OpenTelemetry Distro and supporting APIs.
    using Microsoft.OpenTelemetry;
    
    // Create the application builder.
    var builder = WebApplication.CreateBuilder(args);
    
    // Configure the Microsoft OpenTelemetry Distro.
    builder.UseMicrosoftOpenTelemetry(options =>
    {
      options.Exporters = ExportTarget.AzureMonitor;
    
      // Read the environment setting before the application configuration.
      options.AzureMonitor.ConnectionString =
        builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] ??
        builder.Configuration["AzureMonitor:ConnectionString"];
    });
    
    // Build the application with the configured telemetry services.
    var app = builder.Build();
    
    // Run the application and its telemetry providers.
    app.Run();
    

注意

显式 options.AzureMonitor.ConnectionString 值优先。 配置文件示例在 AzureMonitor 部分之前检查环境变量键。 读取该部分可明确避免依赖隐式配置绑定。

设置云角色名称和云角色实例

适用于 .NET、Node.js 和 Python 的 Microsoft OpenTelemetry 发行版,以及用于 Java 的 Azure Monitor OpenTelemetry,在受支持的情况下检测资源上下文,并为 云角色名称 和云角色实例提供默认值。 你可以为你的应用程序覆盖这些值。 云角色名称在应用程序映射上显示为节点下的名称。

通过 资源 属性设置云角色名称和云角色实例。 云角色名称使用service.namespace和service.name属性,但如果未设置service.name,则回退到service.namespace。 云角色实例使用 service.instance.id 属性值。 有关资源的标准属性的信息,请参阅 OpenTelemetry 语义约定。

设置云角色名称和云角色实例
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Resources;

// Define the service attributes used for cloud role name and instance.
var resourceAttributes = new Dictionary<string, object>
{
    ["service.name"] = "<ServiceName>",
    ["service.namespace"] = "<ServiceNamespace>",
    ["service.instance.id"] = "<ServiceInstanceId>"
};

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()

  // Configure the Microsoft OpenTelemetry Distro.
  .UseMicrosoftOpenTelemetry(options =>
  {
    options.Exporters = ExportTarget.AzureMonitor;
  })

    // Apply the resource attributes to traces, metrics, and logs.
    .ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(
        resourceAttributes));

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

设置资源属性

适用于 .NET、Node.js 和 Python 的 Microsoft OpenTelemetry 发行版,以及用于 Java 的 Azure Monitor OpenTelemetry,可以在受支持的 Azure 环境中启用资源检测。 有关详细信息,请参阅 自动数据收集和资源检测器。

对于手动设置,请使用标准 OpenTelemetry 选项直接设置资源属性:

# Set variables
serviceName="<ServiceName>"
location="<Location>"
subscriptionId="<SubscriptionId>"
resourceGroupName="<ResourceGroupName>"
appName="<AppName>"

# Build App Service resource ID
path="/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
provider="/providers/Microsoft.Web/sites/$appName"
resourceId="$path$provider"

resourceAttributes="cloud.provider=azure,cloud.region=$location"
resourceAttributes+=",cloud.resource_id=$resourceId"
export OTEL_SERVICE_NAME="$serviceName"
export OTEL_RESOURCE_ATTRIBUTES="$resourceAttributes"

在 Windows PowerShell 上:

# Set variables
$serviceName = "<ServiceName>"
$location = "<Location>"
$subscriptionId = "<SubscriptionId>"
$resourceGroupName = "<ResourceGroupName>"
$appName = "<AppName>"

# Build App Service resource ID
$path = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
$provider = "/providers/Microsoft.Web/sites/$appName"
$resourceId = "$path$provider"

$resourceAttributes = "cloud.provider=azure,cloud.region=$location"
$resourceAttributes += ",cloud.resource_id=$resourceId"
$env:OTEL_SERVICE_NAME = $serviceName
$env:OTEL_RESOURCE_ATTRIBUTES = $resourceAttributes

启用采样

采样可减少遥测引入量和成本。 发行版支持Azure Monitor导出的固定百分比采样和速率限制采样。 还可以将应用程序日志与跟踪采样决策保持一致。 采样器将采样信息附加到导出的 Span,以便 Application Insights 可以调整体验次数。 有关概念性概述,请参阅 详细了解采样。

重要

  • 采样决策适用于 跟踪(跨度)。
  • 日志 可以跟随跟踪采样决策。 默认情况下,此行为在适用于 .NET 的 Microsoft OpenTelemetry Distro 中默认启用,并在 Microsoft OpenTelemetry Distro 的 Node.js 和 Python 版本中默认禁用。 请参阅 日志的基于跟踪的采样。
  • 指标从不采样。

注意

如果在 Application Insights 中看到意外费用或高成本,常见原因包括遥测数据量高、数据摄取峰值和配置错误的采样。 若要开始故障排除,请参阅 对 Application Insights 中的高数据引入进行故障排除。

使用环境变量配置采样

使用标准 OpenTelemetry 环境变量来选择采样器,并在你的发行版读取这些环境变量的位置提供其参数。 选择一种配置方法;无需在代码和环境变量中配置相同的采样设置。 按照.NET选项卡中的版本特定指南进行操作。 有关采样器名称的详细信息,请参阅 OTEL_TRACES_SAMPLER。

对于 Microsoft.OpenTelemetry 1.1.0,请使用代码示例在 UseMicrosoftOpenTelemetry() 中设置采样。 也不需要设置 OTEL_TRACES_SAMPLER 或 OTEL_TRACES_SAMPLER_ARG。

以下示例为 Node.js 和Python设置采样环境变量。 对于上述选项卡中涵盖的.NET版本,请改用基于代码的配置。

注意

以下示例对Java无效。 有关正确的环境变量,请参阅上一Java选项卡。

固定百分比采样(约 10%)

export OTEL_TRACES_SAMPLER="microsoft.fixed_percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1

限速采样(~1.5 追踪/秒)

export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5

在代码中配置采样

注意

采样器配置和优先级取决于语言。 .NET示例显式设置发行版选项。 Python使用采样器环境变量。 对于 Node.js,请避免代码和环境中的设置冲突。

固定百分比采样

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Select fixed-percentage sampling instead of rate-limited sampling.
  options.AzureMonitor.TracesPerSecond = null;

  // Keep approximately 10% of traces.
  options.AzureMonitor.SamplingRatio = 0.1F;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

速率限制抽样

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Limit sampling to approximately 1.5 traces per second.
  options.AzureMonitor.TracesPerSecond = 1.5;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

注意

适用于 .NET 的 Microsoft OpenTelemetry 发行版默认采用每秒 5 个跟踪的速率限制采样。 在代码中选择固定百分比采样时,将 TracesPerSecond 设置为 null。

提示

使用固定百分比采样时,不确定为采样率设置的值,从 5% (0.05) 开始。 根据故障和性能窗格中所示操作的准确性来调整速率。 任何采样都降低了准确性,因此 对 OpenTelemetry 指标发出警报,这些指标不受采样影响。

在配置文件中配置采样

在初始化 Microsoft OpenTelemetry 发行版时,从builder.Configuration中读取采样设置并将其分配给options.AzureMonitor.SamplingRatio或options.AzureMonitor.TracesPerSecond 如果选择百分比采样,也设置 TracesPerSecond = null。 验证从 0 到 1 和非负速率限制的比率。 此配置不需要采样器环境变量。

为日志配置基于追踪的采样

启用此功能时,系统会删除属于 未采样跟踪的 日志记录,以便日志与跟踪采样保持一致。

  • 当日志记录具有有效的SpanId时,它是跟踪的一部分。
  • 如果关联的追踪 TraceFlags 指示 未采样,该功能 将删除 日志记录。
  • 不含任何跟踪上下文的日志记录不会受到影响。
  • 默认值取决于语言和发行版版本。 请参阅下面的每种语言设置。

使用以下设置配置基于跟踪的日志采样:

发行版默认启用基于跟踪的日志采样。 将EnableTraceBasedLogsSampler设置为false以禁用它。

// Configure the Microsoft OpenTelemetry Distro.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;
});

实时指标

实时指标提供实时分析仪表板,用于深入了解应用程序活动和性能。

重要

有关适用于 Azure 功能的测试版、预览版或尚未投入正式使用的法律条款,请参阅 Azure 预览补充使用条款。

此功能默认启用。

配置 Microsoft OpenTelemetry 发行版时,可以禁用实时指标。

// Configure the Microsoft OpenTelemetry Distro.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Disable Live Metrics.
  options.AzureMonitor.EnableLiveMetrics = false;
});

脱机存储和自动重试

Azure Monitor 基于 OpenTelemetry 的产品在应用程序与 Application Insights 断开连接时,会缓存遥测数据,并在长达 48 小时内尝试重新发送。 有关数据处理建议,请参阅 导出和删除专用数据。 由于两个原因,高负载应用程序偶尔会删除遥测:超过允许的时间或超过最大文件大小。 如有必要,产品将最近事件优先于旧事件。

Microsoft OpenTelemetry 发行版包括 AzureMonitorExporter,默认情况下,AzureMonitorExporter 使用以下位置之一用于脱机存储(按优先级顺序列出):

  • Windows

    • %LOCALAPPDATA%\Microsoft\AzureMonitor
    • %TEMP%\Microsoft\AzureMonitor
  • 非Windows

    • %TMPDIR%/Microsoft/AzureMonitor
    • /var/tmp/Microsoft/AzureMonitor
    • /tmp/Microsoft/AzureMonitor

若要替代默认目录,请在配置 Microsoft OpenTelemetry 发行版时设置options.AzureMonitor.StorageDirectory。

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

    // Store telemetry here when the exporter cannot send it immediately.
    options.AzureMonitor.StorageDirectory = "<StorageDirectory>";
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

若要禁用此功能,请设置 options.AzureMonitor.DisableOfflineStorage = true。

启用 OTLP 导出器

你可能希望启用 OpenTelemetry 协议(OTLP)导出程序以及Azure Monitor导出程序,以便将遥测数据发送到两个位置。

注意

为方便起见,只展示了 OTLP 导出器。 Azure未正式支持 OTLP 导出程序或其下游的任何组件或第三方体验。

Microsoft OpenTelemetry 发行版包括 OTLP 导出。 使用 OTEL_EXPORTER_OTLP_ENDPOINT 配置收集器终结点,并选择这两个目标:

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  // Send telemetry to Azure Monitor and the configured OTLP collector.
  options.Exporters = ExportTarget.AzureMonitor | ExportTarget.Otlp;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

OpenTelemetry 配置

可以通过环境变量配置以下设置。 使用与你的语言和发行版对应的选项卡。

环境变量 说明
APPLICATIONINSIGHTS_CONNECTION_STRING 将此变量设置为你的 Application Insights 资源的“连接字符串”。
APPLICATIONINSIGHTS_STATSBEAT_DISABLED 将此变量设置为 true 选择退出内部指标集合。
OTEL_RESOURCE_ATTRIBUTES 用于资源属性的键值对。 有关资源属性的详细信息,请参阅资源 SDK 规范。
OTEL_SERVICE_NAME 设置 service.name 资源属性的值。 如果service.name也在OTEL_RESOURCE_ATTRIBUTES中提供,OTEL_SERVICE_NAME将优先。

Redact URL 查询字符串

若要编辑 URL 查询字符串,请禁用查询字符串收集。 如果使用 SAS 令牌调用Azure存储,则建议使用此设置。

Microsoft.OpenTelemetry 发行版包括 ASP.NET Core 和 HttpClient 检测库。 对于处理敏感查询字符串的应用程序,请在初始化 distro 之前显式启用查询脱敏:

  • 将OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION设置为false,用于 ASP.NET Core 检测。
  • 设置 OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION 为 false,用于 HttpClient 检测。

将任一变量设置为 true 将禁用该插桩的查询字符串脱敏。

指标导出间隔

可以使用环境变量配置指标导出间隔 OTEL_METRIC_EXPORT_INTERVAL 。

export OTEL_METRIC_EXPORT_INTERVAL="60000"

默认值为 60000 毫秒(60 秒)。 此设置控制 OpenTelemetry SDK 导出指标的频率。

提示

Azure Monitor指标和Azure Monitor工作区以固定的 60 秒间隔引入自定义指标。 更频繁发送的指标会被缓冲,并每隔 60 秒处理一次。 Log Analytics会根据发送的时间间隔记录指标,短时间间隔可能会增加成本,长时间间隔可能会导致可见性延迟。

有关参考,请参阅以下 OpenTelemetry 规范:

故障排除、反馈和支持

提示

以下部分适用于所有 OpenTelemetry 发行版文章。

故障排除

OpenTelemetry 反馈

若要提供反馈,请查看以下内容:

支持

选择所选语言的选项卡,以发现支持选项。

后续步骤