You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中基于OpenTelemetry对接Azure Application Insights实现分布式追踪

解决方案:将.NET 8 OpenTelemetry追踪迁移到Azure Application Insights

你的现有配置存在重复初始化和导出器冲突的问题,以下是修正后的完整配置方案:

1. 安装必需的NuGet包

确保项目安装了这些包(可通过NuGet包管理器或CLI安装):

  • OpenTelemetry.Exporter.AzureMonitor
  • OpenTelemetry.Instrumentation.AspNetCore
  • OpenTelemetry.Instrumentation.HttpClient
  • OpenTelemetry.Instrumentation.EntityFrameworkCore
  • OpenTelemetry.Extensions.Logging

2. 修正OpenTelemetry配置

移除重复的AddOpenTelemetry调用,统一配置并使用Azure Monitor专属导出器,替代原来的OTLP导出器:

private static void ConfigureOpenTelemetry(WebApplicationBuilder builder, ConfigurationManager config)
{
    var appConfig = builder.Services.BindValidateReturn<DemoCloudServiceOptions>(config);
    var appInsightsConnString = appConfig.AppInsightsConnString;

    // 统一配置OpenTelemetry资源、追踪、指标
    builder.Services.AddOpenTelemetry()
        .ConfigureResource(resource => resource.AddService("MyApp"))
        .WithTracing(tracing =>
        {
            tracing
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddEntityFrameworkCoreInstrumentation()
                // 添加Azure Monitor追踪导出器
                .AddAzureMonitorTraceExporter(options =>
                {
                    options.ConnectionString = appInsightsConnString;
                });
        })
        .WithMetrics(metrics =>
        {
            metrics
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddMeter("MyApp")
                // 添加Azure Monitor指标导出器
                .AddAzureMonitorMetricExporter(options =>
                {
                    options.ConnectionString = appInsightsConnString;
                });
        });

    // 配置日志导出到Azure Monitor
    builder.Logging.AddOpenTelemetry(logging =>
    {
        logging.AddAzureMonitorLogExporter(options =>
        {
            options.ConnectionString = appInsightsConnString;
        });
    });
}

关键说明

  • 移除重复配置:原代码多次调用AddOpenTelemetry()会导致重复注册,合并为一次链式调用即可。
  • 替换导出器:Azure Monitor提供了专门的追踪、指标、日志导出器,无需再使用AddOtlpExporter()(若需同时向多个后端发送数据可保留,但单独对接Application Insights时无需)。
  • 连接字符串验证:确保AppInsightsConnString是从Azure Application Insights实例获取的有效连接字符串,它包含身份验证和端点信息。
  • 服务标识:AddService("MyApp")会在追踪数据中标记服务名称,方便在Application Insights中区分不同服务实例。

配置完成后启动应用,请求数据会自动同步到Azure Application Insights,你可在门户的分布式追踪、指标、日志面板中查看对应信息。

内容的提问来源于stack exchange,提问作者santosh kumar patro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:41:10