您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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.

我们将在此处使用的示例是一个面向 netcoreapp2.2MVC 应用程序The example we'll use here is an MVC application that targets netcoreapp2.2. 可以将这些说明应用于所有 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 App Service、azure VM、Docker、Azure Kubernetes SERVICE (AKS)等的 Web 应用功能。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.0 以及 Application Insights,请使用2.8.0版本或更高版本。If you are using ASP.NET Core 3.0 along with Application Insights, please use the 2.8.0 version or higher. 这是支持 ASP.NET Core 3.0 的唯一版本。This is the only version that supports ASP.NET Core 3.0.

必备条件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. 然后选择 "资源 > Register"。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. 请参阅Project > 管理 NuGet 包 > applicationinsights.config. AspNetCoreGo 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.12.0" />
        </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 应用的应用程序的检测密钥。Typically, APPINSIGHTS_INSTRUMENTATIONKEY specifies the instrumentation key for applications deployed to Azure Web Apps.

    备注

    在代码中指定的检测密钥通过环境变量 APPINSIGHTS_INSTRUMENTATIONKEY,后者 wins 超过其他选项。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).
  • SDK 版本2.7.1 和更高版本,如果应用程序在 Windows 和目标 NETSTANDARD2.0 或更高版本中运行,则会收集性能计数器。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 环境)中获取系统计数器的建议方法是使用EventCountersThe recommended way to get system counters in Linux (and other non-Windows environments) is by using EventCounters

EventCounterEventCounter

默认情况下启用 EventCounterCollectionModule,它将从 .NET Core 3.0 应用程序收集默认的计数器集。EventCounterCollectionModule is enabled by default, and it will collect a default set of counters from .NET Core 3.0 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中,在 "<head>" 部分的末尾,但在其他任何脚本之前插入 HtmlHelperIn _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>
    

或者,若要使用 FullScript ScriptBody 可从 SDK v 2.14 开始使用。Alternatively 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:

```cshtml
    <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 ASP.NET SDK 的用户可能熟悉如何使用 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 SDK 添加到应用程序,并使用 ASP.NET Core 内置依赖关系注入对其进行配置。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

您可以通过将 ApplicationInsightsServiceOptions 传递到 AddApplicationInsightsTelemetry来修改几个常见设置,如以下示例中所示: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
EnableQuickPulseMetricStreamEnableQuickPulseMetricStream 启用/禁用 LiveMetrics 功能Enable/Disable LiveMetrics feature truetrue
EnableAdaptiveSamplingEnableAdaptiveSampling 启用/禁用自适应采样Enable/Disable Adaptive Sampling truetrue
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. truetrue
AddAutoCollectedMetricExtractorAddAutoCollectedMetricExtractor 启用/禁用 AutoCollectedMetrics 提取程序,它是一种 TelemetryProcessor,它在采样发生之前发送有关请求/依赖项的预聚合度量值。Enable/Disable AutoCollectedMetrics extractor, which is a TelemetryProcessor that sends pre-aggregated metrics about Requests/Dependencies before sampling takes place. truetrue
RequestCollectionOptions.TrackExceptionsRequestCollectionOptions.TrackExceptions 启用/禁用请求收集模块报告未处理的异常跟踪。Enable/Disable reporting of unhandled Exception tracking by the Request collection module. NETSTANDARD 2.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.

添加 TelemetryInitializersAdding TelemetryInitializers

若要定义随所有遥测发送的全局属性,请使用遥测初始值设定项Use telemetry initializers when you want to define global properties that are sent with all telemetry.

DependencyInjection 容器添加任何新 TelemetryInitializer,如以下代码所示。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>();
}

删除 TelemetryInitializersRemoving 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>();
}

配置或删除默认 TelemetryModulesConfiguring 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-收集遥测数据,以便在 Live 指标门户中显示。QuickPulseTelemetryModule - Collects telemetry for showing in Live Metrics portal.
  • AppServicesHeartbeatTelemetryModule 收集用于托管应用程序 Azure App Service 环境的心节拍(以自定义指标的形式发送)。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);
    }
}

配置遥测通道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.0?Does Application Insights support ASP.NET Core 3.0?

是的。Yes. 更新APPLICATION INSIGHTS SDK 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.0。Older versions of the SDK do not support ASP.NET Core 3.0.

此外,如果使用的是基于 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.0 应用程序的自动载入。Previous versions of Visual Studio do not support automatic onboarding for ASP.NET Core 3.0 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 的单一实例,该实例与其他遥测数据 TelemetryConfiguration 共享。A 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.0 应用程序中,services.AddApplicationInsightsTelemetry() 是启用 application insights 的唯一方法。Also, in ASP.NET Core 3.0 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.0 辅助角色服务模板应用程序是否支持此 SDK?Is this SDK supported for the new .NET Core 3.0 Worker Service template applications?

此 SDK 需要 HttpContext,因此不能在任何非 HTTP 应用程序(包括 .NET Core 3.0 辅助服务应用程序)中使用。This SDK requires HttpContext, and hence does not work in any non-HTTP applications, including the .NET Core 3.0 Worker Service applications. 请参阅文档,了解如何使用新发布的 APPLICATIONINSIGHTS.CONFIG 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.

视频Video

后续步骤Next steps