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

本文介绍如何为 ASP.NET Core 应用程序启用 Application Insights。This article describes how to enable Application Insights for an ASP.NET Core application. 完成本文中所述的步骤后,Application Insights 将从 ASP.NET Core 应用程序收集请求、依赖项、异常、性能计数器、检测信号和日志。When you complete the instructions in this article, Application Insights will collect requests, dependencies, exceptions, performance counters, heartbeats, and logs from your ASP.NET Core application.

本文所用的示例是一个面向 netcoreapp3.0MVC 应用程序The example we'll use here is an MVC application that targets netcoreapp3.0. 这些说明适用于所有 ASP.NET Core 应用程序。You can apply these instructions to all ASP.NET Core applications.

支持的方案Supported scenarios

无论在何处以何种方式运行你的应用程序,适用于 ASP.NET Core 的 Application Insights SDK 都可对其进行监视。The Application Insights SDK for ASP.NET Core can monitor your applications no matter where or how they run. 如果应用程序正在运行并与 Azure 建立了网络连接,则可以收集遥测数据。If your application is running and has network connectivity to Azure, telemetry can be collected. 只要支持 .NET Core,就能支持 Application Insights 监视。Application Insights monitoring is supported everywhere .NET Core is supported. 支持范围包括:Support covers:

  • 操作系统:Windows、Linux 或 Mac。Operating system: Windows, Linux, or Mac.
  • 托管方法:进程内或进程外。Hosting method: In process or out of process.
  • 部署方法:框架相关或独立。Deployment method: Framework dependent or self-contained.
  • Web 服务器:IIS (Internet Information Server) 或 Kestrel。Web server: IIS (Internet Information Server) or Kestrel.
  • 托管平台:Azure 应用服务的 Web 应用功能、Azure VM、Docker、Azure Kubernetes 服务 (AKS) 等。Hosting platform: The Web Apps feature of Azure App Service, Azure VM, Docker, Azure Kubernetes Service (AKS), and so on.
  • .NET Core 运行时版本:1.XX、2.XX 或 3.XX.NET Core Runtime version: 1.XX, 2.XX, or 3.XX
  • IDE:Visual Studio、VS Code 或命令行。IDE: Visual Studio, VS Code, or command line.

备注

ASP.NET Core 3.X 需要 Application Insights 2.8.0 或更高版本。ASP.NET Core 3.X requires Application Insights 2.8.0 or later.

先决条件Prerequisites

  • 一个正常运行的 ASP.NET Core 应用程序。A functioning ASP.NET Core application. 如果需要创建 ASP.NET Core 应用程序,请遵循此 ASP.NET Core 教程If you need to create an ASP.NET Core application, follow this ASP.NET Core tutorial.
  • 有效的 Application Insights 检测密钥。A valid Application Insights instrumentation key. 将任何遥测数据发送到 Application Insights 都需要使用此密钥。This key is required to send any telemetry to Application Insights. 如果需要创建新的 Application Insights 资源来获取检测密钥,请参阅创建 Application Insights 资源If you need to create a new Application Insights resource to get an instrumentation key, see Create an Application Insights resource.

启用 Application Insights 服务器端遥测 (Visual Studio)Enable Application Insights server-side telemetry (Visual Studio)

  1. 在 Visual Studio 中打开项目。Open your project in Visual Studio.

    提示

    如果需要,可为项目设置源代码管理,以便可以跟踪 Application Insights 做出的所有更改。If you want to, you can set up source control for your project so you can track all the changes that Application Insights makes. 若要启用源代码管理,请选择“文件” > “添加到源代码管理”。 To enable source control, select File > Add to Source Control.

  2. 选择“项目” > “添加 Application Insights 遥测” 。Select Project > Add Application Insights Telemetry.

  3. 选择“入门”。Select Get Started. 选项文本根据 Visual Studio 版本的不同而异。This selection's text might vary, depending on your version of Visual Studio. 在某些早期版本中,使用的是“免费开始”按钮。Some earlier versions use a Start Free button instead.

  4. 选择订阅。Select your subscription. 然后选择“资源” > “注册”。 Then select Resource > Register.

  5. 将 Application Insights 添加到项目后,确认使用的是最新稳定版本的 SDK。After adding Application Insights to your project, check to confirm that you're using the latest stable release of the SDK. 转到“项目” > “管理 NuGet 包” > “Microsoft.ApplicationInsights.AspNetCore”。 Go to Project > Manage NuGet Packages > Microsoft.ApplicationInsights.AspNetCore. 根据需要选择“更新”。If you need to, choose Update.

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

  6. 如果你已遵循可选的提示操作并已将项目添加到源代码管理,请转到“视图” > “团队资源管理器” > “更改”。 If you followed the optional tip and added your project to source control, go to View > Team Explorer > Changes. 然后选择每个文件,以查看 Application Insights 遥测功能所做的更改的差异视图。Then select each file to see a diff view of the changes made by Application Insights telemetry.

启用 Application Insights 服务器端遥测(不使用 Visual Studio)Enable Application Insights server-side telemetry (no Visual Studio)

  1. 安装适用于 ASP.NET Core 的 Application Insights SDK NuGet 包Install the Application Insights SDK NuGet package for ASP.NET Core. 我们建议始终使用最新稳定版本。We recommend that you always use the latest stable version. 开源 GitHub 存储库中可以找到 SDK 的完整发行说明。Find full release notes for the SDK on the open-source GitHub repo.

    以下代码示例演示了要添加到项目的 .csproj 文件中的更改。The following code sample shows the changes to be added to your project's .csproj file.

        <ItemGroup>
          <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.13.1" />
        </ItemGroup>
    
  2. services.AddApplicationInsightsTelemetry(); 添加到 Startup 类中的 ConfigureServices() 方法,如以下示例所示:Add services.AddApplicationInsightsTelemetry(); to the ConfigureServices() method in your Startup class, as in this example:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();
    
            // This code adds other services for your application.
            services.AddMvc();
        }
    
  3. 设置检测密钥。Set up the instrumentation key.

    尽管可将检测密钥作为参数提供给 AddApplicationInsightsTelemetry,但我们建议在配置中指定检测密钥。Although you can provide the instrumentation key as an argument to AddApplicationInsightsTelemetry, we recommend that you specify the instrumentation key in configuration. 以下代码示例演示如何在 appsettings.json 中指定检测密钥。The following code sample shows how to specify an instrumentation key in appsettings.json. 在发布期间,请确保将 appsettings.json 复制到应用程序根文件夹。Make sure appsettings.json is copied to the application root folder during publishing.

        {
          "ApplicationInsights": {
            "InstrumentationKey": "putinstrumentationkeyhere"
          },
          "Logging": {
            "LogLevel": {
              "Default": "Warning"
            }
          }
        }
    

    或者,在以下任一环境变量中指定检测密钥:Alternatively, specify the instrumentation key in either of the following environment variables:

    • APPINSIGHTS_INSTRUMENTATIONKEY

    • ApplicationInsights:InstrumentationKey

    例如:For example:

    • SET ApplicationInsights:InstrumentationKey=putinstrumentationkeyhere

    • SET APPINSIGHTS_INSTRUMENTATIONKEY=putinstrumentationkeyhere

    • APPINSIGHTS_INSTRUMENTATIONKEY 通常在 Azure Web 应用中使用,但也可以在所有支持此 SDK 的平台使用。APPINSIGHTS_INSTRUMENTATIONKEY is typically used in Azure Web Apps, but can also be used in all places where this SDK is supported. (如果要执行无代码 Web 应用监视,则在不使用连接字符串的情况下必须使用此格式。)(If you are doing codeless web app monitoring, this format is required if you aren't using connection strings.)

    现在,也可以使用连接字符串来代替设置检测密钥。In lieu of setting instrumentation keys you can now also use Connection Strings.

    备注

    在代码中指定的检测密钥优先于环境变量 APPINSIGHTS_INSTRUMENTATIONKEY,而后者又优先于其他选项。An instrumentation key specified in code wins over the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, which wins over other options.

运行应用程序Run your application

运行应用程序并向其发出请求。Run your application and make requests to it. 现在,遥测数据应会流入 Application Insights。Telemetry should now flow to Application Insights. Application Insights SDK 自动将传入的 Web 请求收集到应用程序,并收集以下遥测数据。The Application Insights SDK automatically collects incoming web requests to your application, along with the following telemetry as well.

实时指标Live Metrics

实时指标可用于快速验证是否正确配置了 Application Insights 监视。Live Metrics can be used to quickly verify if Application Insights monitoring is configured correctly. 尽管可能需要在几分钟时间后遥测数据才开始显示在门户和分析结果中,但实时指标能够近实时地显示正在运行的进程的 CPU 使用率。While it might take a few minutes before telemetry starts appearing in the portal and analytics, Live Metrics would show CPU usage of the running process in near real-time. 它还可以显示其他遥测数据,例如请求、依赖项、跟踪等。It can also show other telemetry like Requests, Dependencies, Traces, etc.

ILogger 日志ILogger logs

自动捕获通过 Warning 或更高严重性的 ILogger 发出的日志。Logs emitted via ILogger of severity Warning or greater are automatically captured. 遵循 ILogger 文档自定义 Application Insights 捕获的日志级别。Follow ILogger docs to customize which log levels are captured by Application Insights.

依赖项Dependencies

默认情况已启用依赖项收集。Dependency collection is enabled by default. 此文介绍了自动收集的依赖项,并提供了执行手动跟踪的步骤。This article explains the dependencies that are automatically collected, and also contain steps to do manual tracking.

性能计数器Performance counters

对 ASP.NET Core 中的性能计数器的支持限制如下:Support for performance counters in ASP.NET Core is limited:

  • 如果应用程序在 Azure Web 应用 (Windows) 中运行,则 SDK 2.4.1 和更高版本将收集性能计数器。SDK versions 2.4.1 and later collect performance counters if the application is running in Azure Web Apps (Windows).
  • 如果应用程序在 Windows 中运行,并且面向 NETSTANDARD2.0 或更高版本,则 SDK 2.7.1 和更高版本将收集性能计数器。SDK versions 2.7.1 and later collect performance counters if the application is running in Windows and targets NETSTANDARD2.0 or later.
  • 对于面向 .NET Framework 的应用程序,所有版本的 SDK 都支持性能计数器。For applications targeting the .NET Framework, all versions of the SDK support performance counters.
  • SDK 2.8.0 版和更高版本支持 Linux 中的 cpu/内存计数器。SDK Versions 2.8.0 and later support cpu/memory counter in Linux. Linux 不支持其他计数器。No other counter is supported in Linux. 在 Linux(和其他非 Windows 环境)中,获取系统计数器的建议方法是使用 EventCounterThe recommended way to get system counters in Linux (and other non-Windows environments) is by using EventCounters

EventCounterEventCounter

EventCounterCollectionModule 默认已启用,它会从 .NET Core 3.X 应用收集默认的计数器集。EventCounterCollectionModule is enabled by default, and it will collect a default set of counters from .NET Core 3.X apps. EventCounter 教程列出了收集的默认计数器集。The EventCounter tutorial lists the default set of counters collected. 它还包含有关自定义列表的说明。It also has instructions on customizing the list.

为 Web 应用程序启用客户端遥测Enable client-side telemetry for web applications

完成前面所述的步骤足以开始收集服务器端遥测数据。The preceding steps are enough to help you start collecting server-side telemetry. 如果应用程序包含客户端组件,请遵循后续步骤开始收集使用情况遥测数据If your application has client-side components, follow the next steps to start collecting usage telemetry.

  1. _ViewImports.cshtml 中添加注入代码:In _ViewImports.cshtml, add injection:

        @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    
  2. _Layout.cshtml 中,将 HtmlHelper 插入到 <head> 节的末尾、任何其他脚本的前面。In _Layout.cshtml, insert HtmlHelper at the end of the <head> section but before any other script. 若要从页面报告任何自定义 JavaScript 遥测数据,请将其注入到此片段的后面:If you want to report any custom JavaScript telemetry from the page, inject it after this snippet:

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

从 SDK v2.14 开始,除了使用 FullScript 之外,还可以使用 ScriptBodyAlternatively to using the FullScript the ScriptBody is available starting in SDK v2.14. 如果需要控制 <script> 标记以设置内容安全策略,请使用此标记:Use this if you need to control the <script> tag to set a Content Security Policy:

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

前面引用的 .cshtml 文件名取自默认的 MVC 应用程序模板。The .cshtml file names referenced earlier are from a default MVC application template. 从根本上讲,若要为应用程序正确启用客户端监视,JavaScript 代码片段必须出现在所要监视的应用程序的每个页面的 <head> 节中。Ultimately, if you want to properly enable client-side monitoring for your application, the JavaScript snippet must appear in the <head> section of each page of your application that you want to monitor. 将 JavaScript 代码片段添加到 _Layout.cshtml 即可实现此应用程序模板的此目标。You can accomplish this goal for this application template by adding the JavaScript snippet to _Layout.cshtml.

如果项目不包含 _Layout.cshtml,你仍然可以添加客户端监视If your project doesn't include _Layout.cshtml, you can still add client-side monitoring. 为此,可将 JavaScript 代码片段添加到用于控制应用中所有页面的 <head> 的等效文件。You can do this by adding the JavaScript snippet to an equivalent file that controls the <head> of all pages within your app. 或者,可将代码片段添加到多个页面中,但这种解决方法很难掌控,因此我们一般不建议。Or you can add the snippet to multiple pages, but this solution is difficult to maintain and we generally don't recommend it.

配置 Application Insights SDKConfigure the Application Insights SDK

可以自定义适用于 ASP.NET Core 的 Application Insights SDK 以更改默认配置。You can customize the Application Insights SDK for ASP.NET Core to change the default configuration. Application Insights SDK ASP.NET 的用户可以使用 ApplicationInsights.config 或通过修改 TelemetryConfiguration.Active 来熟悉配置更改。Users of the Application Insights ASP.NET SDK might be familiar with changing configuration by using ApplicationInsights.config or by modifying TelemetryConfiguration.Active. 对于 ASP.NET Core,需以不同的方式更改配置。You change configuration differently for ASP.NET Core. 使用 ASP.NET Core 的内置依赖项注入将 ASP.NET Core SDK 添加到应用程序并对其进行配置。Add the ASP.NET Core SDK to the application and configure it by using ASP.NET Core built-in dependency injection. 除非另有指示,否则几乎所有的配置更改都是在 Startup.cs 类的 ConfigureServices() 方法中完成的。Make almost all configuration changes in the ConfigureServices() method of your Startup.cs class, unless you're directed otherwise. 以下部分提供了详细信息。The following sections offer more information.

备注

在 ASP.NET Core 应用程序中,不支持通过修改 TelemetryConfiguration.Active 来更改配置。In ASP.NET Core applications, changing configuration by modifying TelemetryConfiguration.Active isn't supported.

使用 ApplicationInsightsServiceOptionsUsing ApplicationInsightsServiceOptions

可以通过向 AddApplicationInsightsTelemetry 传递 ApplicationInsightsServiceOptions 来修改一些通用设置,如以下示例所示:You can modify a few common settings by passing ApplicationInsightsServiceOptions to AddApplicationInsightsTelemetry, as in this example:

public void ConfigureServices(IServiceCollection services)
{
    Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
    // Disables adaptive sampling.
    aiOptions.EnableAdaptiveSampling = false;

    // Disables QuickPulse (Live Metrics stream).
    aiOptions.EnableQuickPulseMetricStream = false;
    services.AddApplicationInsightsTelemetry(aiOptions);
}

ApplicationInsightsServiceOptions 中的完整设置列表Full List of settings in ApplicationInsightsServiceOptions

设置Setting 说明Description 默认Default
EnablePerformanceCounterCollectionModuleEnablePerformanceCounterCollectionModule 启用/禁用 PerformanceCounterCollectionModuleEnable/Disable PerformanceCounterCollectionModule true
EnableRequestTrackingTelemetryModuleEnableRequestTrackingTelemetryModule 启用/禁用 RequestTrackingTelemetryModuleEnable/Disable RequestTrackingTelemetryModule true
EnableEventCounterCollectionModuleEnableEventCounterCollectionModule 启用/禁用 EventCounterCollectionModuleEnable/Disable EventCounterCollectionModule true
EnableDependencyTrackingTelemetryModuleEnableDependencyTrackingTelemetryModule 启用/禁用 DependencyTrackingTelemetryModuleEnable/Disable DependencyTrackingTelemetryModule true
EnableAppServicesHeartbeatTelemetryModuleEnableAppServicesHeartbeatTelemetryModule 启用/禁用 AppServicesHeartbeatTelemetryModuleEnable/Disable AppServicesHeartbeatTelemetryModule true
EnableAzureInstanceMetadataTelemetryModuleEnableAzureInstanceMetadataTelemetryModule 启用/禁用 AzureInstanceMetadataTelemetryModuleEnable/Disable AzureInstanceMetadataTelemetryModule true
EnableQuickPulseMetricStreamEnableQuickPulseMetricStream Enable/Disable LiveMetrics featureEnable/Disable LiveMetrics feature true
EnableAdaptiveSamplingEnableAdaptiveSampling 启用/禁用自适应采样Enable/Disable Adaptive Sampling true
EnableHeartbeatEnableHeartbeat 启用/禁用检测信号功能,该功能定期(默认间隔为 15 分钟)发送名为“HeartbeatState”的自定义指标,其中包含有关运行时等的信息,例如 .NET 版本、Azure 环境信息(如果适用)等。Enable/Disable Heartbeats feature, which periodically (15-min default) sends a custom metric named 'HeartbeatState' with information about the runtime like .NET Version, Azure Environment information, if applicable, etc. true
AddAutoCollectedMetricExtractorAddAutoCollectedMetricExtractor 启用/禁用 AutoCollectedMetrics 提取程序 - 一个 TelemetryProcessor,在采样发生之前发送有关请求/依赖项的聚合前指标。Enable/Disable AutoCollectedMetrics extractor, which is a TelemetryProcessor that sends pre-aggregated metrics about Requests/Dependencies before sampling takes place. true
RequestCollectionOptions.TrackExceptionsRequestCollectionOptions.TrackExceptions 启用/禁用请求收集模块的未经处理的异常跟踪报告。Enable/Disable reporting of unhandled Exception tracking by the Request collection module. 在 NETSTANDARD2.0 中为 false(因为异常是通过 ApplicationInsightsLoggerProvider 跟踪的),否则为 true。false in NETSTANDARD2.0 (because Exceptions are tracked with ApplicationInsightsLoggerProvider), true otherwise.

有关最新列表,请参阅 ApplicationInsightsServiceOptions 中的可配置设置See the configurable settings in ApplicationInsightsServiceOptions for the most up-to-date list.

采样Sampling

适用于 ASP.NET Core 的 Application Insights SDK 支持固定频率和自适应采样。The Application Insights SDK for ASP.NET Core supports both fixed-rate and adaptive sampling. 自适应采样默认已启用。Adaptive sampling is enabled by default.

有关详细信息,请参阅 配置 ASP.NET Core 应用程序的自适应采样For more information, see Configure adaptive sampling for ASP.NET Core applications.

添加 TelemetryInitializerAdding TelemetryInitializers

若要定义连同所有遥测数据一起发送的全局属性,请使用遥测初始化表达式Use telemetry initializers when you want to define global properties that are sent with all telemetry.

将任何新的 TelemetryInitializer 添加到 DependencyInjection 容器,如以下代码所示。Add any new TelemetryInitializer to the DependencyInjection container as shown in the following code. SDK 会自动拾取添加到 DependencyInjection 容器的任何 TelemetryInitializerThe SDK automatically picks up any TelemetryInitializer that's added to the DependencyInjection container.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();
}

删除 TelemetryInitializerRemoving TelemetryInitializers

默认已提供遥测初始化表达式。Telemetry initializers are present by default. 若要删除所有或特定的遥测初始化表达式,请在调用 AddApplicationInsightsTelemetry() 之后使用以下示例代码。To remove all or specific telemetry initializers, use the following sample code after you call AddApplicationInsightsTelemetry().

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();

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

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

添加遥测处理程序Adding telemetry processors

可以使用 IServiceCollection 中的扩展方法 AddApplicationInsightsTelemetryProcessor 将自定义遥测处理程序添加到 TelemetryConfigurationYou can add custom telemetry processors to TelemetryConfiguration by using the extension method AddApplicationInsightsTelemetryProcessor on IServiceCollection. 高级筛选方案中使用遥测处理器。You use telemetry processors in advanced filtering scenarios. 使用以下示例。Use the following example.

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddApplicationInsightsTelemetry();
    services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();

    // If you have more processors:
    services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();
}

配置或删除默认的 TelemetryModuleConfiguring or removing default TelemetryModules

Application Insights 使用遥测模块自动收集有关特定工作负荷的有用遥测数据,无需用户手动跟踪。Application Insights uses telemetry modules to automatically collect useful telemetry about specific workloads without requiring manual tracking by user.

默认已启用以下自动收集模块。The following automatic-collection modules are enabled by default. 这些模块负责自动收集遥测数据。These modules are responsible for automatically collecting telemetry. 可以禁用或配置这些模块,以改变其默认行为。You can disable or configure them to alter their default behavior.

  • RequestTrackingTelemetryModule - 从传入的 Web 请求收集 RequestTelemetry。RequestTrackingTelemetryModule - Collects RequestTelemetry from incoming web requests.
  • DependencyTrackingTelemetryModule - 从传出的 http 调用和 sql 调用收集 DependencyTelemetry。DependencyTrackingTelemetryModule - Collects DependencyTelemetry from outgoing http calls and sql calls.
  • PerformanceCollectorModule - 收集 Windows PerformanceCounters。PerformanceCollectorModule - Collects Windows PerformanceCounters.
  • QuickPulseTelemetryModule - 收集遥测数据以便在实时指标门户中显示。QuickPulseTelemetryModule - Collects telemetry for showing in Live Metrics portal.
  • AppServicesHeartbeatTelemetryModule - 收集有关托管应用程序的 Azure 应用服务环境的检测信号(以自定义指标的形式发送)。AppServicesHeartbeatTelemetryModule - Collects heart beats (which are sent as custom metrics), about Azure App Service environment where application is hosted.
  • AzureInstanceMetadataTelemetryModule - 收集有关托管应用程序的 Azure VM 环境的检测信号(以自定义指标的形式发送)。AzureInstanceMetadataTelemetryModule - Collects heart beats (which are sent as custom metrics), about Azure VM environment where application is hosted.
  • EventCounterCollectionModule - 收集 EventCounters.EventCounterCollectionModule - Collects EventCounters. 此模块是一项新功能,可在 SDK 版本 2.8.0 及更高版本中使用。This module is a new feature and is available in SDK Version 2.8.0 and higher.

若要配置任何默认的 TelemetryModule,请按以下示例中所示使用 IServiceCollection 中的扩展方法 ConfigureTelemetryModule<T>To configure any default TelemetryModule, use the extension method ConfigureTelemetryModule<T> on IServiceCollection, as shown in the following example.

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();

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

    // The following removes all default counters from EventCounterCollectionModule, and adds a single one.
    services.ConfigureTelemetryModule<EventCounterCollectionModule>(
            (module, o) =>
            {
                module.Counters.Clear();
                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 = services.FirstOrDefault<ServiceDescriptor>(t => t.ImplementationType == typeof(PerformanceCollectorModule));
    if (performanceCounterService != null)
    {
        services.Remove(performanceCounterService);
    }
}

从 2.12.2 版本开始,ApplicationInsightsServiceOptions 包含用于禁用默认模块的简单选项。Starting with 2.12.2 version, ApplicationInsightsServiceOptions contains easy option to disable any of the default modules.

配置遥测通道Configuring a telemetry channel

默认通道为 ServerTelemetryChannelThe default channel is ServerTelemetryChannel. 可按以下示例所示替代该通道。You can override it as the following example shows.

using Microsoft.ApplicationInsights.Channel;

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

        services.AddApplicationInsightsTelemetry();
    }

动态禁用遥测Disable telemetry dynamically

如果要有条件和动态地禁用遥测,可以在代码中的任何位置使用 ASP.NET Core 依赖项注入容器解析 TelemetryConfiguration 实例,并在其上设置 DisableTelemetry 标志。If you want to disable telemetry conditionally and dynamically, you may resolve TelemetryConfiguration instance with ASP.NET Core dependency injection container anywhere in your code and set DisableTelemetry flag on it.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
    {
        configuration.DisableTelemetry = true;
        ...
    }

上述操作不会阻止任何自动收集模块收集遥测数据。The above does not prevent any auto collection modules from collecting telemetry. 使用上述方法只会禁止向 Application Insights 发送遥测数据。Only the sending of telemetry to Application Insights gets disabled with the above approach. 如果不需要某个特定的自动收集模块,最好是删除遥测模块If a particular auto collection module is not desired, it is best to remove the telemetry module

常见问题Frequently asked questions

Application Insights 是否支持 ASP.NET Core 3.X?Does Application Insights support ASP.NET Core 3.X?

是的。Yes. 请更新到 Application Insights SDK for ASP.NET Core 2.8.0 或更高版本。Update to Application Insights SDK for ASP.NET Core version 2.8.0 or higher. 更低的 SDK 版本不支持 ASP.NET Core 3.X。Older versions of the SDK do not support ASP.NET Core 3.X.

此外,如果使用此处基于 Visual Studio 的说明,请更新到最新版本的 Visual Studio 2019 (16.3.0) 以完成加入。Also, if you are using Visual Studio based instructions from here, update to the latest version of Visual Studio 2019 (16.3.0) to onboard. 旧版 Visual Studio 不支持 ASP.NET Core 3.X 应用的自动加入。Previous versions of Visual Studio do not support automatic onboarding for ASP.NET Core 3.X apps.

如何跟踪不会自动收集的遥测数据?How can I track telemetry that's not automatically collected?

使用构造函数注入获取 TelemetryClient 的实例,然后对其调用所需的 TrackXXX() 方法。Get an instance of TelemetryClient by using constructor injection, and call the required TrackXXX() method on it. 我们不建议在 ASP.NET Core 应用程序中创建新的 TelemetryClient 实例。We don't recommend creating new TelemetryClient instances in an ASP.NET Core application. DependencyInjection 容器中已注册了 TelemetryClient 的单一实例,该实例与剩余的遥测功能共享 TelemetryConfigurationA singleton instance of TelemetryClient is already registered in the DependencyInjection container, which shares TelemetryConfiguration with rest of the telemetry. 仅当需要与剩余的遥测功能使用不同的配置时,才建议创建新的 TelemetryClient 实例。Creating a new TelemetryClient instance is recommended only if it needs a configuration that's separate from the rest of the telemetry.

以下示例演示如何从控制器跟踪其他遥测数据。The following example shows how to track additional telemetry from a controller.

using Microsoft.ApplicationInsights;

public class HomeController : Controller
{
    private TelemetryClient telemetry;

    // Use constructor injection to get a TelemetryClient instance.
    public HomeController(TelemetryClient telemetry)
    {
        this.telemetry = telemetry;
    }

    public IActionResult Index()
    {
        // Call the required TrackXXX method.
        this.telemetry.TrackEvent("HomePageRequested");
        return View();
    }

有关 Application Insights 中自定义数据报告的详细信息,请参阅 Application Insights 自定义指标 API 参考For more information about custom data reporting in Application Insights, see Application Insights custom metrics API reference.

某些 Visual Studio 模板使用 IWebHostBuilder 中的 UseApplicationInsights() 扩展方法来启用 Application Insights。Some Visual Studio templates used the UseApplicationInsights() extension method on IWebHostBuilder to enable Application Insights. 这种用法是否仍然有效?Is this usage still valid?

尽管 UseApplicationInsights() 扩展方法仍受支持,但它在 Application Insights SDK 版本 2.8.0 中已标记为弃用。While the extension method UseApplicationInsights() is still supported, it is marked obsolete in Application Insights SDK version 2.8.0 onwards. 在下一个 SDK 主要版本中,将会删除此方法。It will be removed in the next major version of the SDK. 启用 Application Insights 遥测的建议方式是使用 AddApplicationInsightsTelemetry(),因为它提供用于控制某个配置的重载。The recommended way to enable Application Insights telemetry is by using AddApplicationInsightsTelemetry() because it provides overloads to control some configuration. 此外,在 ASP.NET Core 3.X 应用中,services.AddApplicationInsightsTelemetry() 是启用 Application Insights 的唯一方式。Also, in ASP.NET Core 3.X apps, services.AddApplicationInsightsTelemetry() is the only way to enable application insights.

我正在将 ASP.NET Core 应用程序部署到 Web 应用。I'm deploying my ASP.NET Core application to Web Apps. 是否仍要从 Web 应用启用 Application Insights 扩展?Should I still enable the Application Insights extension from Web Apps?

如果在生成时已按本文所示安装了 SDK,则无需从应用服务门户启用 Application Insights 扩展If the SDK is installed at build time as shown in this article, you don't need to enable the Application Insights extension from the App Service portal. 即使安装了扩展,在检测到已将 SDK 添加到应用程序时,该扩展也仍会回退。Even if the extension is installed, it will back off when it detects that the SDK is already added to the application. 如果从扩展启用 Application Insights,则无需安装和更新 SDK。If you enable Application Insights from the extension, you don't have to install and update the SDK. 但是,遵照本文中的说明启用 Application Insights 会更灵活,原因如下:But if you enable Application Insights by following instructions in this article, you have more flexibility because:

  • Application Insights 遥测功能将在以下位置或模式下继续运行:Application Insights telemetry will continue to work in:
    • 所有操作系统,包括 Windows、Linux 和 Mac。All operating systems, including Windows, Linux, and Mac.
    • 所有发布模式,包括“独立”或“框架相关”。All publish modes, including self-contained or framework dependent.
    • 所有目标框架,包括完整的 .NET Framework。All target frameworks, including the full .NET Framework.
    • 所有托管选项,包括 Web 应用、VM、Linux、容器、Azure Kubernetes 服务和非 Azure 托管。All hosting options, including Web Apps, VMs, Linux, containers, Azure Kubernetes Service, and non-Azure hosting.
    • 所有 .NET Core 版本,包括预览版。All .NET Core versions including preview versions.
  • 从 Visual Studio 调试时,可在本地查看遥测数据。You can see telemetry locally when you're debugging from Visual Studio.
  • 可以使用 TrackXXX() API 跟踪其他自定义遥测数据。You can track additional custom telemetry by using the TrackXXX() API.
  • 可以完全控制配置。You have full control over the configuration.

是否可以使用状态监视器之类的工具来启用 Application Insights 监视?Can I enable Application Insights monitoring by using tools like Status Monitor?

否。No. 状态监视器状态监视器 v2 目前仅支持 ASP.NET 4.x。Status Monitor and Status Monitor v2 currently support ASP.NET 4.x only.

系统是否会自动为 ASP.NET Core 2.0 应用程序启用 Application Insights?Is Application Insights automatically enabled for my ASP.NET Core 2.0 application?

Microsoft.AspNetCore.All 2.0 元包包含 Application Insights SDK(版本 2.1.0)。The Microsoft.AspNetCore.All 2.0 metapackage included the Application Insights SDK (version 2.1.0). 如果在 Visual Studio 调试器中运行该应用程序,则 Visual Studio 会启用 Application Insights,并在 IDE 本身中显示遥测数据。If you run the application under Visual Studio debugger, Visual Studio enables Application Insights and shows telemetry locally in the IDE itself. 除非指定检测密钥,否则遥测数据不会发送到 Application Insights 服务。Telemetry wasn't sent to the Application Insights service unless an instrumentation key was specified. 我们建议遵照本文中的说明启用 Application Insights,即使是对于 2.0 应用。We recommend following the instructions in this article to enable Application Insights, even for 2.0 apps.

如果在 Linux 中运行应用程序,是否支持所有功能?If I run my application in Linux, are all features supported?

是的。Yes. SDK 的功能支持在所有平台中是相同的,不过存在以下例外情况:Feature support for the SDK is the same in all platforms, with the following exceptions:

  • 该 SDK 在 Linux 上收集事件计数器,因为性能计数器仅在 Windows 中受支持。The SDK collects Event Counters on Linux because Performance Counters are only supported in Windows. 大多数指标是相同的。Most metrics are the same.
  • 尽管默认已启用 ServerTelemetryChannel,但如果应用程序在 Linux 或 MacOS 中运行,出现网络问题时,通道不会自动创建本地存储文件夹来暂时保留遥测数据。Even though ServerTelemetryChannel is enabled by default, if the application is running in Linux or MacOS, the channel doesn't automatically create a local storage folder to keep telemetry temporarily if there are network issues. 由于这种限制,在出现暂时性的网络或服务器时,遥测数据将会丢失。Because of this limitation, telemetry is lost when there are temporary network or server issues. 若要解决此问题,请为通道配置一个本地文件夹:To work around this issue, configure a local folder for the channel:
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;

    public void ConfigureServices(IServiceCollection services)
    {
        // The following will configure the channel to use the given folder to temporarily
        // store telemetry items during network or Application Insights server issues.
        // User should ensure that the given folder already exists
        // and that the application has read/write permissions.
        services.AddSingleton(typeof(ITelemetryChannel),
                                new ServerTelemetryChannel () {StorageFolder = "/tmp/myfolder"});
        services.AddApplicationInsightsTelemetry();
    }

新的 .NET Core 3.X 辅助角色服务模板应用程序是否支持此 SDK?Is this SDK supported for the new .NET Core 3.X Worker Service template applications?

此 SDK 需要 HttpContext,因此在任何非 HTTP 应用程序(包括 .NET Core 3.X 辅助角色服务应用程序)中无法正常工作。This SDK requires HttpContext, and hence does not work in any non-HTTP applications, including the .NET Core 3.X Worker Service applications. 有关如何使用新发布的 Microsoft.ApplicationInsights.WorkerService SDK 在此类应用程序中启用 Application Insights,请参阅此文档Refer to this document for enabling application insights in such applications, using the newly released Microsoft.ApplicationInsights.WorkerService SDK.

开源 SDKOpen-source SDK

阅读代码或为其做出贡献Read and contribute to the code.

后续步骤Next steps