Leer en inglés

Compartir a través de

适用于 ASP.NET Core 应用程序的 Application Insights

本文介绍如何为 ASP.NET Core 应用程序启用和配置 Application Insights。

Precaución

我们建议新应用程序或客户使用 Azure Monitor OpenTelemetry 发行版来支持 Azure Monitor Application Insights。 Azure Monitor OpenTelemetry 发行版提供与 Application Insights SDK 类似的功能和体验。 可以使用 .NETNode.jsPython 的迁移指南从 Application Insights SDK 进行迁移,但我们仍在努力添加更多功能以实现后向兼容性。

Application Insights 可以从你的 ASP.NET Core 应用程序收集以下遥测数据:

  • 请求
  • 依赖项
  • 异常
  • 性能计数器
  • 检测信号
  • 日志

我们将使用一个 MVC 应用程序示例。 如果你使用的是辅助角色服务,请使用适用于辅助角色服务应用程序的 Application Insights 中的说明。

提供基于 OpenTelemetry 的 .NET 产品/服务。 有关详细信息,请参阅 OpenTelemetry 概述

Nota

对检测密钥引入的支持将于 2025 年 3 月 31 日结束。 检测密钥引入功能将会继续工作,但我们将不再为该功能提供更新或支持。 转换为连接字符串,以利用新功能

Nota

如果要使用独立的 ILogger 提供程序,请使用 Microsoft.Extensions.Logging.ApplicationInsight

支持的方案

无论在何处以何种方式运行你的应用程序,适用于 ASP.NET Core 的 Application Insights SDK 都可对其进行监视。 如果应用程序正在运行并与 Azure 建立了网络连接,则可以收集遥测数据。 Application Insights 监视在任何支持 .NET Core 的地方都受支持,并涵盖以下方案:

  • 操作系统:Windows、Linux 或 Mac
  • 托管方法:进程内或进程外
  • 部署方法:框架依赖或自包含
  • Web 服务器:Internet Information Server (IIS) 或 Kestrel
  • 托管平台:Azure 应用服务的 Web 应用功能、Azure 虚拟机、Docker 和 Azure Kubernetes 服务 (AKS)
  • .NET 版本:所有并非处于预览状态的官方支持的 .NET 版本
  • IDE:Visual Studio、Visual Studio Code 或命令行

先决条件

  • 一个正常运行的 ASP.NET Core 应用程序。 如果需要创建 ASP.NET Core 应用程序,请遵循此 ASP.NET Core 教程
  • 对受支持版本的 Application Insights NuGet 包的引用。
  • 一个有效的 Application Insights 连接字符串。 将任何遥测数据发送到 Application Insights 时,都需要使用此字符串。 如果你需要创建新的 Application Insights 资源来获取连接字符串,请参阅创建 Application Insights 资源

启用 Application Insights 服务器端遥测 (Visual Studio)

对于 Visual Studio for Mac,请使用手动指南。 只有 Windows 版本的 Visual Studio 支持此过程。

  1. 在 Visual Studio 中打开项目。

  2. 转到“项目”>“添加 Application Insights 遥测”。

  3. 选择“Azure Application Insights”>“下一步”。

  4. 选择订阅和 Application Insights 实例。 也可使用“新建”创建一个新实例。 选择“下一步”。

  5. 添加或确认 Application Insights 连接字符串。 系统应该会根据你在上一步的选择对它进行预填充。 选择“完成”。

  6. 将 Application Insights 添加到项目后,确认使用的是最新稳定版本的 SDK。 转到“项目”>“管理 NuGet 包”>“Microsoft.ApplicationInsights.AspNetCore”。 如果需要,请选择“更新”。

    屏幕截图显示在何处选择要更新的 Application Insights 包。

启用 Application Insights 服务器端遥测(不使用 Visual Studio)

  1. 安装适用于 ASP.NET Core 的 Application Insights SDK NuGet 包

    我们建议始终使用最新稳定版本。 在开源 GitHub 存储库中可以找到 SDK 的完整发行说明。

    以下代码示例演示了要添加到项目的 .csproj 文件中的更改:

    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    </ItemGroup>
    
  2. AddApplicationInsightsTelemetry() 添加到你的 program.cs 类。

    builder.Services.AddApplicationInsightsTelemetry(); 方法后添加 WebApplication.CreateBuilder(),如以下示例所示:

    // This method gets called by the runtime. Use this method to add services to the container.
    var builder = WebApplication.CreateBuilder(args);
    
    // The following line enables Application Insights telemetry collection.
    builder.Services.AddApplicationInsightsTelemetry();
    
    // This code adds other services for your application.
    builder.Services.AddMvc();
    
    var app = builder.Build();
    
  3. 添加连接字符串,可以通过三种方式完成:

    • (建议)在配置中设置连接字符串。

      appsettings.json 中设置连接字符串,并确保在发布过程中将配置文件复制到应用程序根文件夹。

      {
          "Logging": {
              "LogLevel": {
                  "Default": "Information",
                  "Microsoft.AspNetCore": "Warning"
              }
          },
          "AllowedHosts": "*",
          "ApplicationInsights": {
              "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
          }
      }
      
    • APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量或 JSON 配置文件中的 ApplicationInsights:ConnectionString 中设置连接字符串。

      例如:

      • SET ApplicationInsights:ConnectionString = <Copy connection string from Application Insights Resource Overview>
      • SET APPLICATIONINSIGHTS_CONNECTION_STRING = <Copy connection string from Application Insights Resource Overview>
      • 通常,APPLICATIONINSIGHTS_CONNECTION_STRING 用在 Web 应用中。 它也可以在所有支持此 SDK 的地方使用。

      Nota

      在代码中指定的连接字符串优先于环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING,而后者又优先于其他选项。

    • 在代码中设置连接字符串。

      ApplicationInsightsServiceOptions 类中,将连接字符串作为 AddApplicationInsightsTelemetry 参数的一部分提供给

用户机密和其他配置提供程序

如果你要将连接字符串存储在 ASP.NET Core 用户机密中,或者要从其他配置提供程序中检索它,可以将重载与 Microsoft.Extensions.Configuration.IConfiguration 参数一起使用。 示例参数为 services.AddApplicationInsightsTelemetry(Configuration);

Microsoft.ApplicationInsights.AspNetCore 版本 2.15.0 及更高版本中,调用 services.AddApplicationInsightsTelemetry() 会自动从应用程序的 Microsoft.Extensions.Configuration.IConfiguration 中读取连接字符串。 无需显式提供 IConfiguration

如果 IConfiguration 已从多个提供程序加载配置,则无论添加提供程序的顺序如何,services.AddApplicationInsightsTelemetry 都会优先考虑 appsettings.json 中的配置。 使用 services.AddApplicationInsightsTelemetry(IConfiguration) 方法从 IConfiguration 读取配置,而无需对 appsettings.json 进行这种优先处理。

运行应用程序

运行应用程序并向其发出请求。 现在,遥测数据应会流入 Application Insights。 Application Insights SDK 自动将传入的 Web 请求收集到应用程序,并收集以下遥测数据。

实时指标

实时指标可用于快速验证是否正确配置了使用 Application Insights 的应用程序监视。 遥测数据可能需要几分钟才能出现在 Azure 门户中,但实时指标窗格会近乎实时地显示正在运行的进程的 CPU 使用情况。 它还可以显示其他遥测,例如请求、依赖项和跟踪。

使用代码为任何 .NET 应用程序启用实时指标

Nota

按照建议用于 .NET 应用程序的说明加入实时指标时,将会默认启用它。

若要手动配置实时指标,请执行以下操作:

  1. 安装 NuGet 包 Microsoft.ApplicationInsights.PerfCounterCollector

  2. 以下示例控制台应用代码显示了如何设置实时指标:

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;

// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
QuickPulseTelemetryProcessor quickPulseProcessor = null;
config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
    .Use((next) =>
    {
        quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
        return quickPulseProcessor;
    })
    .Build();

var quickPulseModule = new QuickPulseTelemetryModule();

// Secure the control channel.
// This is optional, but recommended.
quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
quickPulseModule.Initialize(config);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);

// Create a TelemetryClient instance. It is important
// to use the same TelemetryConfiguration here as the one
// used to set up live metrics.
TelemetryClient client = new TelemetryClient(config);

// This sample runs indefinitely. Replace with actual application logic.
while (true)
{
    // Send dependency and request telemetry.
    // These will be shown in live metrics.
    // CPU/Memory Performance counter is also shown
    // automatically without any additional steps.
    client.TrackDependency("My dependency", "target", "http://sample",
        DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
    client.TrackRequest("My Request", DateTimeOffset.Now,
        TimeSpan.FromMilliseconds(230), "200", true);
    Task.Delay(1000).Wait();
}

上述示例适用于控制台应用,但在所有 .NET 应用程序中都可以使用相同的代码。 如果启用了自动收集遥测数据的任何其他遥测模块,请务必确保用于初始化这些模块的相同配置也用于实时指标模块。

ILogger 日志

默认配置收集 ILoggerWarning 日志和严重性级别更高的日志。 有关详细信息,请参阅如何自定义 ILogger 日志收集?

依赖项

默认情况已启用依赖项收集。 Application Insights 中的依赖项跟踪介绍了自动收集的依赖项,以及执行手动跟踪的步骤。

性能计数器

对 ASP.NET Core 中的性能计数器的支持限制如下:

  • 如果应用程序在 Web 应用 (Windows) 中运行,则 SDK 2.4.1 和更高版本将收集性能计数器。
  • 如果应用程序在 Windows 中运行且面向的是 netstandard2.0 或更高版本,则 SDK 版本 2.7.1 及更高版本将收集性能计数器。
  • 对于面向 .NET Framework 的应用程序,所有版本的 SDK 都支持性能计数器。
  • SDK 2.8.0 及更高版本在 Linux 中支持 CPU/内存计数器。 但不在 Linux 中支持其他计数器。 若要获取 Linux 和其他非 Windows 环境中的系统计数器,请使用 EventCounter

EventCounter

默认情况下,启用 EventCounterCollectionModule。 若要了解如何配置要收集的计数器列表,请参阅 EventCounters 简介

通过 HTTP 扩充数据

HttpContext.Features.Get<RequestTelemetry>().Properties["myProp"] = someData

为 Web 应用程序启用客户端遥测

完成前面所述的步骤足以开始收集服务器端遥测数据。 如果应用程序具有客户端组件,请按照后续步骤开始使用 JavaScript (Web) SDK 加载程序脚本注入通过配置来收集用量遥测数据

  1. _ViewImports.cshtml 中,添加注入:

    @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    
  2. _Layout.cshtml 中,将 HtmlHelper 插入到 <head> 节的末尾、任何其他脚本的前面。 若要从页面报告任何自定义 JavaScript 遥测数据,请将其注入到此片段的后面:

        @Html.Raw(JavaScriptSnippet.FullScript)
    </head>
    

作为 FullScript 的替代方法,ScriptBody 从 Application Insights SDK for ASP.NET Core 版本 2.14 开始提供。 如果需要控制 ScriptBody 标记以设置内容安全策略,请使用 <script>

<script> // apply custom changes to this script tag.
    @Html.Raw(JavaScriptSnippet.ScriptBody)
</script>

前面引用的 .cshtml 文件名取自默认的 MVC 应用程序模板。 从根本上讲,若要为应用程序正确启用客户端监视,JavaScript (Web) SDK 加载程序脚本必须出现在所要监视的应用程序的每个页面的 <head> 部分中。 在应用程序模板中,将 JavaScript (Web) SDK 加载程序脚本添加到 _Layout.cshtml 以启用客户端监视。

如果你的项目不包含 _Layout.cshtml,仍可通过将 JavaScript (Web) SDK 加载程序脚本添加到控制应用内所有页面的 的等效文件来添加<head>。 或者,可将 JavaScript (Web) SDK 加载程序脚本添加到多个页面中,但我们不建议这样做。

Nota

JavaScript 注入提供默认配置体验。 除了设置连接字符串以外,如果还需要其他配置,你需要删除所述的自动注入并手动添加 JavaScript SDK

配置 Application Insights SDK

可以自定义适用于 ASP.NET Core 的 Application Insights SDK 以更改默认配置。 Application Insights ASP.NET SDK 的用户可以使用 ApplicationInsights.config 或通过修改 TelemetryConfiguration.Active 来熟悉配置更改。 对于 ASP.NET Core,除非另有说明,否则在 ConfigureServices() 类的 方法中进行几乎所有配置更改。 以下部分提供了详细信息。

Nota

在 ASP.NET Core 应用程序中,不支持通过修改 TelemetryConfiguration.Active 来更改配置。

使用 ApplicationInsightsServiceOptions

可以通过向 ApplicationInsightsServiceOptions 传递 AddApplicationInsightsTelemetry 来修改一些通用设置,如以下示例所示:

var builder = WebApplication.CreateBuilder(args);

var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

// Disables adaptive sampling.
aiOptions.EnableAdaptiveSampling = false;

// Disables live metrics (also known as QuickPulse).
aiOptions.EnableQuickPulseMetricStream = false;

builder.Services.AddApplicationInsightsTelemetry(aiOptions);
var app = builder.Build();

此表包含 ApplicationInsightsServiceOptions 设置的完整列表:

设置 说明 默认
启用性能计数器收集模块 启用/禁用 PerformanceCounterCollectionModule 真 实
启用请求跟踪遥测模块 (EnableRequestTrackingTelemetryModule) 启用/禁用 RequestTrackingTelemetryModule 真 实
启用事件计数器收集模块 启用/禁用 EventCounterCollectionModule 真 实
启用依赖追踪遥测模块 启用/禁用 DependencyTrackingTelemetryModule 真 实
启用应用服务心跳遥测模块 启用/禁用 AppServicesHeartbeatTelemetryModule 真 实
启用Azure实例元数据遥测模块 启用/禁用 AzureInstanceMetadataTelemetryModule 真 实
启用快速脉冲指标流 启用/禁用 LiveMetrics 功能。 真 实
启用自适应采样 启用/禁用自适应采样。 真 实
EnableHeartbeat 启用/禁用检测信号功能。 它定期(默认间隔为 15 分钟)发送名为 HeartbeatState 的自定义指标,其中包含有关运行时的信息,例如 .NET 版本、Azure 环境信息(如果适用)。 真 实
AddAutoCollectedMetricExtractor 启用/禁用 AutoCollectedMetrics extractor。 此遥测处理器在采样发生之前发送有关请求/依赖项的预聚合指标。 真 实
RequestCollectionOptions.TrackExceptions 启用/禁用请求收集模块的未经处理的异常跟踪报告。 netstandard2.0 中为 false(因为异常是通过 ApplicationInsightsLoggerProvider 跟踪的)。 否则为 true。
启用诊断遥测模块 启用/禁用 DiagnosticsTelemetryModule。 禁用会导致以下设置被忽略:EnableHeartbeatEnableAzureInstanceMetadataTelemetryModuleEnableAppServicesHeartbeatTelemetryModule 真 实

有关最新列表,请参阅ApplicationInsightsServiceOptions 中的可配置设置

针对 Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 及更高版本的配置建议

在 Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 及更高版本中,配置 ApplicationInsightsServiceOptions 中提供的每个设置,包括 ConnectionString。 使用应用程序的 IConfiguration 实例。 设置必须位于 ApplicationInsights 节下,如以下示例所示。 appsettings.json 的以下节配置连接字符串,并禁用自适应采样和性能计数器收集。

{
    "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000",
    "EnableAdaptiveSampling": false,
    "EnablePerformanceCounterCollectionModule": false
    }
}

如果使用 builder.Services.AddApplicationInsightsTelemetry(aiOptions) (适用于 ASP.NET Core 6.0)或 services.AddApplicationInsightsTelemetry(aiOptions)(适用于 ASP.NET Core 3.1 及更早版本),它会覆盖来自 Microsoft.Extensions.Configuration.IConfiguration 的设置。

采样

适用于 ASP.NET Core 的 Application Insights SDK 支持固定频率和自适应采样。 默认情况下,启用自适应采样。

有关详细信息,请参阅 配置 ASP.NET Core 应用程序的自适应采样

添加 TelemetryInitializer

如果要使用其他信息来扩充遥测,请使用遥测初始化表达式

将任何新的 TelemetryInitializer 添加到 DependencyInjection 容器,如以下代码所示。 SDK 会自动拾取添加到 TelemetryInitializer 容器的任何 DependencyInjection

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();

var app = builder.Build();

Nota

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>(); 适用于简单的初始化程序。 对于其他程序,builder.Services.AddSingleton(new MyCustomTelemetryInitializer() { fieldName = "myfieldName" }); 是必需的。

删除 TelemetryInitializer

默认情况下,提供遥测初始化表达式。 若要删除所有或特定的遥测初始化表达式,请在调用 AddApplicationInsightsTelemetry()使用以下示例代码。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// Remove a specific built-in telemetry initializer
var tiToRemove = builder.Services.FirstOrDefault<ServiceDescriptor>
                    (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));
if (tiToRemove != null)
{
    builder.Services.Remove(tiToRemove);
}

// Remove all initializers
// This requires importing namespace by using Microsoft.Extensions.DependencyInjection.Extensions;
builder.Services.RemoveAll(typeof(ITelemetryInitializer));

var app = builder.Build();

添加遥测处理器

可以使用 TelemetryConfiguration 中的扩展方法 AddApplicationInsightsTelemetryProcessor 将自定义遥测处理程序添加到 IServiceCollection。 在高级筛选方案中使用遥测处理器。 使用以下示例:

var builder = WebApplication.CreateBuilder(args);

// ...
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();

// If you have more processors:
builder.Services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();

var app = builder.Build();

配置或删除默认 TelemetryModule

Application Insights 自动收集有关特定工作负荷的遥测数据,无需用户手动跟踪。

默认情况下,启用以下自动收集模块。 这些模块负责自动收集遥测数据。 可以禁用或配置这些模块,以改变其默认行为。

  • RequestTrackingTelemetryModule:从传入 Web 请求收集 RequestTelemetry。
  • DependencyTrackingTelemetryModule:从传出 HTTP 调用和 SQL 调用收集 DependencyTelemetry
  • PerformanceCollectorModule:收集 Windows PerformanceCounter。
  • QuickPulseTelemetryModule:收集要在实时指标窗格中显示的遥测。
  • AppServicesHeartbeatTelemetryModule:收集有关托管应用程序的应用服务环境的检测信号(以自定义指标的形式发送)。
  • AzureInstanceMetadataTelemetryModule:收集有关托管应用程序的 Azure VM 环境的检测信号(以自定义指标的形式发送)。
  • EventCounterCollectionModule:收集 EventCounter。 此模块是一项新功能,可在 SDK 2.8.0 及更高版本中使用。

若要配置任何默认的 TelemetryModule,请按以下示例所示使用 ConfigureTelemetryModule<T> 中的扩展方法 IServiceCollection

using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// The following configures DependencyTrackingTelemetryModule.
// Similarly, any other default modules can be configured.
builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
        {
            module.EnableW3CHeadersInjection = true;
        });

// The following removes all default counters from EventCounterCollectionModule, and adds a single one.
builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>((module, o) =>
        {
            module.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
        });

// The following removes PerformanceCollectorModule to disable perf-counter collection.
// Similarly, any other default modules can be removed.
var performanceCounterService = builder.Services.FirstOrDefault<ServiceDescriptor>(t => t.ImplementationType == typeof(PerformanceCollectorModule));
if (performanceCounterService != null)
{
    builder.Services.Remove(performanceCounterService);
}

var app = builder.Build();

在版本 2.12.2 及更高版本中,ApplicationInsightsServiceOptions 包含一个简单选项,用于禁用任何默认模块。

配置遥测通道

默认遥测通道ServerTelemetryChannel。 下面的示例演示如何对其进行替代。

using Microsoft.ApplicationInsights.Channel;

var builder = WebApplication.CreateBuilder(args);

// Use the following to replace the default channel with InMemoryChannel.
// This can also be applied to ServerTelemetryChannel.
builder.Services.AddSingleton(typeof(ITelemetryChannel), new InMemoryChannel() {MaxTelemetryBufferCapacity = 19898 });

builder.Services.AddApplicationInsightsTelemetry();

var app = builder.Build();

Nota

如果要刷新缓冲区,请参阅刷新数据。 例如,如果在关闭的应用程序中使用 SDK,可能需要刷新缓冲区。

动态禁用遥测

如果要有条件和动态地禁用遥测,可以在代码中的任何位置使用 ASP.NET Core 依赖项注入容器解析 TelemetryConfiguration 实例,并在其上设置 DisableTelemetry 标志。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// any custom configuration can be done here:
builder.Services.Configure<TelemetryConfiguration>(x => x.DisableTelemetry = true);

var app = builder.Build();

前面的代码示例阻止将遥测数据发送到 Application Insights。 它不会阻止任何自动收集模块收集遥测数据。 如果要删除特定的自动收集模块,请参阅删除遥测模块

故障排除

请参阅专用疑难解答文章

测试应用程序主机与引入服务之间的连接性

Application Insights SDK 和代理发送遥测,将其作为 REST 调用引入到引入终结点。 可以使用原始 REST 客户端通过 PowerShell 或使用 curl 命令,测试从 Web 服务器或应用程序主机计算机到引入服务终结点的连接。 请参阅排查 Azure Monitor Application Insights 中缺失应用程序遥测的问题

开源 SDK

阅读代码或为其做出贡献

有关最新的更新和 bug 修补程序,请参阅发行说明

发行说明

对于版本 2.12 及更高版本:.NET SDK(包括 ASP.NET、ASP.NET Core 和日志记录适配器)

我们的服务更新还总结了 Application Insights 的主要改进。

后续步骤