【Azure Developer】ASP.NET Framework 4.8 集成 Azure Application Insights SDK 完整指南

简介: 本文详解如何在老旧的.NET Framework 4.8项目中集成Azure Application Insights SDK(推荐2.23.0版),实现请求追踪、异常捕获与性能监控。涵盖SDK选型、NuGet安装、Connection String配置、web.config模块注册、自定义遥测及数据验证,并提醒Auto-Instrumentation冲突等常见问题。

前言

在生产环境中,应用性能监控是保障系统稳定运行的关键一环,特别是部署到云上的服务,但是,由于.Net Framework 4.8项目年代久远,无法实现一些无代码的方式集成获取日志数据。

而Azure Application Insights提供了两种方式:无代码 , 集成SDK的方式来实现日志收集。它提供了强大的请求追踪、依赖调用分析、异常捕获和性能指标收集能力。所以本文将详细介绍如何在 ASP.NET Framework 4.8 项目中集成 Application Insights SDK。


选择正确的 SDK 版本

ASP.NET Framework 与 ASP.NET Core 使用不同的 NuGet 包,请勿混淆:

框架

NuGet 包

当前推荐版本

ASP.NET Framework 4.6.2+

Microsoft.ApplicationInsights.Web

2.22.x

ASP.NET Core

Microsoft.ApplicationInsights.AspNetCore

2.22.x

Worker Service / Console

Microsoft.ApplicationInsights.WorkerService

2.22.x

 

对于 .NET Framework 4.8 项目,我们使用 Microsoft.ApplicationInsights.Web

注意:请使用 Microsoft.ApplicationInsights.Web  2.23.0

安装该包后会自动引入以下组件:

  • Microsoft.ApplicationInsights — 核心 SDK,提供 TelemetryClient
  • Microsoft.AI.Web — 自动追踪 HTTP 请求和响应
  • Microsoft.AI.DependencyCollector — 自动追踪 SQL 查询、HTTP 外部调用等依赖项
  • Microsoft.AI.PerfCounterCollector — 收集 CPU、内存等性能计数器
  • Microsoft.AspNet.TelemetryCorrelation — 分布式追踪关联

 

集成步骤

第一步:安装 NuGet 包

在 Visual Studio 中打开 Package Manager Console,执行:

Install-Package Microsoft.ApplicationInsights.Web -Version 2.23.0

或者通过 NuGet Package Manager UI 搜索 Microsoft.ApplicationInsights.Web 并安装2.23.0版。

 

第二步:配置 Connection String

安装完成后,项目根目录会自动生成 ApplicationInsights.config 文件。

打开该文件,配置 Connection String:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<ConnectionString>InstrumentationKey=xx-x-x-x-xxx;EndpointSuffix=applicationinsights.azure.cn;IngestionEndpoint=https://chinanorth3-0.in.applicationinsights.azure.cn/;LiveEndpoint=https://chinanorth3.livediagnostics.monitor.azure.cn/;AADAudience=https://monitor.azure.cn/;ApplicationId= xx-x-x-x-xxx </ConnectionString>
  <TelemetryInitializers>
    <!-- 自动生成的初始化器配置 -->
  </TelemetryInitializers>
  <TelemetryModules>
    <!-- 自动生成的模块配置 -->
  </TelemetryModules>
</ApplicationInsights>

PS:示例使用的是中国区的Azure Application Insights 服务,所以Connection String指向中国区 endpoint:IngestionEndpoint=https://dc.applicationinsights.azure.cn/;LiveEndpoint=https://live.applicationinsights.azure.cn/

也可以使用环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING来保存连接字符串。

 

第三步:验证 web.config 配置

NuGet 包安装时会自动修改 web.config,添加两个关键的 HTTP Module。

请确认以下配置存在:

<configuration>
  <system.webServer>
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule"
           type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation"
           preCondition="managedHandler" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking"
           type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
           preCondition="managedHandler" />
    </modules>
  </system.webServer>
</configuration>

提示:这两个 Module 的顺序很重要 — TelemetryCorrelationHttpModule 必须在前,负责分布式追踪的上下文传播。

第四步:发送自定义遥测数据(可选)

SDK 安装后,请求、依赖、异常等已自动收集。

如需发送自定义事件或指标:


using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
public class OrderController : Controller
{
    private readonly TelemetryClient _telemetryClient = new TelemetryClient();

            // 追踪自定义事件
            _telemetryClient.TrackEvent("test event", new Dictionary<string, string>
            {
                { "event ID", Guid.NewGuid().ToString() },
                { "event Title", "this is custome events title 20260514"   }
            });
            // 追踪自定义指标
            _telemetryClient.TrackMetric("customer metrics", (new Random()).NextDouble());

}

 

第五步:验证数据上报

1. 本地运行项目,触发几个页面请求

2. 打开 Azure Portal → Application Insights 资源

3. 进入Search,确认能看到请求遥测数据

 

4. 检查 Live Metrics,确认实时数据流正常

注意:数据从应用发送到 Portal 通常有 2-5 分钟延迟,Live Metrics 则是实时的。

 

常见问题与注意事项

1. App Service Auto-Instrumentation 冲突

如果你的应用部署在 Azure App Service 上,并且开启了 Application Insights 的 Auto-Instrumentation(代码无侵入式监控),不要同时在代码中安装 SDK。两者同时存在会导致:

  • 重复的遥测数据
  • 性能下降
  • 依赖追踪异常

 

解决方案:二选一。推荐使用 SDK 方式(更灵活可控),并将 App Service 的 ApplicationInsightsAgent_EXTENSION_VERSION 设为 disabled。

2. 采样配置

生产环境中高流量场景下,建议配置自适应采样以控制成本:

<ApplicationInsights>
  <TelemetryProcessors>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
      <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
    </Add>
  </TelemetryProcessors>
</ApplicationInsights>


3. 关于 OpenTelemetry 迁移

微软目前推荐新项目使用 OpenTelemetry + Azure.Monitor.OpenTelemetry.Exporter。但该方案目前仅支持 ASP.NET Core。对于 .NET Framework 4.8 项目,Classic SDK(Microsoft.ApplicationInsights.Web)仍是官方支持的方案,短期内不会被废弃。

4. SDK 诊断日志

如遇到数据不上报的问题,可开启 SDK 自诊断:

<TelemetryModules>
  <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.FileDiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
    <Severity>Verbose</Severity>
    <LogFileName>ai-sdk-diag.txt</LogFileName>
    <LogFilePath>D:\home\LogFiles\ApplicationInsights</LogFilePath>
  </Add>
</TelemetryModules>


 

总结

步骤

操作

1

安装 Microsoft.ApplicationInsights.Web NuGet 包

2

在 ApplicationInsights.config 中配置 Connection String

或添加环境变量APPLICATIONINSIGHTS_CONNECTION_STRING

3

确认 web.config 中 HTTP Module 已正确注册

4

(可选)通过 TelemetryClient 发送自定义遥测

5

在 Azure Portal 验证数据上报

 




当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

相关文章
|
1月前
|
NoSQL 网络协议 Cloud Native
【Azure Redis】云原生环境下的 Redis 超时之谜:为什么 15 分钟后应用才恢复?
云原生中Redis短暂不可用后应用持续超时15分钟?问题不在Redis,而在Linux TCP默认重传机制(tcp_retries2=15)与长连接模型的错位。需三管齐下:调低内核重传次数、客户端显式配置超时与自动重连、应用层引入断路器与弹性重试。
165 20
|
1月前
|
前端开发 应用服务中间件 Linux
【Azure App Service】PHP页面上传文件413错误的解决方案
在使用 Azure App Service(Linux + PHP) 部署 Web 应用时,如果上传文件大于1MB,就会遇到 HTTP 413(Request Entity Too Large) 错误。 # 问题解答 ### 一、HTTP 413 错误的本质含义 413 Request Entity Too Large 是标准 HTTP 状态码,表示: > 客户端提交的请求体(Request Body)大小超过了服务器当前允许的最大限制。 在 Azure App Service(Linux)环境中,这个错误并不一定来自前端网关(Frontend),而更常见的来源是 App...
772 13
|
1天前
|
存储 人工智能 JSON
Litefuse 正式发布:Agent 可观测与效果评估, 比 Langfuse 成本低 88%
Litefuse 是一个 Agent 可观测与评估平台,兼容 Langfuse SDK 和 100 多个 AI 生态,并支持 Hermes、OpenClaw、Claude Code 等通用 Agent。存储成本比 Langfuse 降低 88%、简化部署架构、Trace 文本检索效率提升 10 倍,帮助团队以更低成本构建可靠的观测平台。
97 9
Litefuse 正式发布:Agent 可观测与效果评估, 比 Langfuse 成本低 88%
|
3天前
|
运维 安全 容器
【Azure Container App】容器应用的维护窗口设置
Azure Container Apps 平台会自动执行维护更新,分关键(即时)与非关键(可预约)两类。可通过 CLI 为环境配置计划维护窗口(8–24 小时),将非关键更新约束在业务低峰期,降低影响。该功能仅适用于工作负载配置档环境。
|
4天前
|
存储 SQL 网络协议
【Azure 应用服务】WEBSITE_DISABLE_CROSS_STAMP_SCALE 配置的作用说明
`WEBSITE_DISABLE_CROSS_STAMP_SCALE` 是 Azure App Service/Function App 的平台级配置,用于禁用同一区域内跨 Stamp(扩展单元)的实例调度,以减少因位置差异导致的 DNS、网络或连接问题。它并非 DNS 或超时修复开关,而是排查网络不稳定的“隔离变量”工具,需配合 VNet、DNS、防火墙等配置综合诊断。(239字)
|
13天前
|
存储 缓存 Linux
【Azure App Service】为什么 Web App 上的文件会被"锁死"?
Azure App Service中,/home目录文件可能出现“僵尸锁”:stat显示Links:0,文件已删但句柄未释放,导致无法删除/移动、FTP/Kudu失效、重启无效。根因是Azure Files远程存储的SMB会话未断开。推荐绕过方案:复制文件+更新引用+重启应用。
|
15天前
|
容器
【Azure Container App】使用 yaml 部署 Container App 时遇见 400 Bad Request 错误
使用 `az containerapp create --yaml` 时,CLI 扩展会将未定义字段序列化为 `null`,导致 ARM 反序列化失败(如 `allowInsecure: null` 被误转为布尔值),引发 400 错误。解决方案:在 YAML 中显式设置 `allowInsecure: false` 等必填/非空字段。
195 3
|
16天前
|
开发工具 Windows
【App Service】查看Application Insights自身SDK日志的方法示例
本文介绍当App Service启用Application Insights后仍无遥测数据时,可启用其自诊断功能:通过Kudu添加`ApplicationInsightsDiagnostics.json`配置文件,设置日志路径、大小与级别(Verbose),重启应用后按新PID查看详细日志,快速定位SDK初始化或传输失败原因。(239字)
|
24天前
|
人工智能 监控 网络协议
【App Service】常规排查 App Service 启动 Application Insights 无数据的步骤 (.NET版本)
本文详解Application Insights在Azure App Service中无日志数据的三大原因及排查方法:1)网络连通性(验证到AI端点的443端口访问);2)w3wp.exe进程是否成功加载AI模块;3)DLL冲突(检查并移除重复的Microsoft.ApplicationInsights等组件)。
132 10
|
1月前
|
数据采集 开发框架 监控
【Azure Developer】IIS w3wp.exe 的 -m 参数:一个未被记录的管道模式标识
本文揭秘了IIS中未公开的`w3wp.exe -m`启动参数:`-m 0`表示Integrated管道模式(推荐),`-m 1`为Classic模式。该发现源于Application Insights自动检测失效的排查,解释了其为何不支持Classic模式——因HttpModule无法全面拦截请求。
145 12