使用 ApplicationInsights.config 或 .xml 配置 Application Insights SDKConfiguring the Application Insights SDK with ApplicationInsights.config or .xml

Application Insights .NET SDK 由多个 NuGet 包组成。The Application Insights .NET SDK consists of a number of NuGet packages. 核心包提供 API,用于将遥测数据发送到 Application Insights。The core package provides the API for sending telemetry to the Application Insights. 其他包提供遥测模块初始值设定项,用于自动从应用程序及其上下文跟踪遥测。Additional packages provide telemetry modules and initializers for automatically tracking telemetry from your application and its context. 可以通过调整配置文件来启用或禁用遥测模块和初始值设定项并为其设置参数。By adjusting the configuration file, you can enable or disable Telemetry Modules and initializers, and set parameters for some of them.

配置文件名为 ApplicationInsights.configApplicationInsights.xml,具体取决于应用程序的类型。The configuration file is named ApplicationInsights.config or ApplicationInsights.xml, depending on the type of your application. 安装大多数版本的 SDK 时,系统会自动将配置文件添加到项目。It is automatically added to your project when you install most versions of the SDK. 默认情况下,使用支持“添加”>“添加 Application Insights 遥测”的 Visual Studio 模板项目提供的自动化体验时,ApplicationInsights.config 文件在项目根文件夹中创建,在编译后复制到 bin 文件夹。By default, when using the automated experience from the Visual Studio template projects that support Add > Application Insights Telemetry, the ApplicationInsights.config file is created in the project root folder and when complied is copied to the bin folder. 通过使用 IIS 服务器上的状态监视器,也会将配置文件添加到 Web 应用。It is also added to a web app by Status Monitor on an IIS server. 如果使用了 Azure 网站的扩展Azure VM 和虚拟机规模集的扩展,则会忽略此配置文件。The configuration file is ignored if extension for Azure website or extension for Azure VM and virtual machine scale set is used.

没有等效的文件可以控制网页中的 SDKThere isn't an equivalent file to control the SDK in a web page.

本文档说明配置文件中显示的节、控制 SDK 组件的方式,以及哪些 NuGet 包会加载这些组件。This document describes the sections you see in the configuration file, how they control the components of the SDK, and which NuGet packages load those components.


ApplicationInsights.config 和 .xml 指令不适用于 .NET Core SDK。ApplicationInsights.config and .xml instructions do not apply to the .NET Core SDK. 若要配置 .NET Core 应用程序,请遵循指南。For configuring .NET Core applications, follow this guide.

遥测模块 (ASP.NET)Telemetry Modules (ASP.NET)

每个遥测模块收集特定类型的数据,并使用核心 API 来发送数据。Each Telemetry Module collects a specific type of data and uses the core API to send the data. 不同的 NuGet 包会安装这些模块,同时在 .config 文件中添加所需的行。The modules are installed by different NuGet packages, which also add the required lines to the .config file.

在配置文件中,每个模块都有一个对应的节点。There's a node in the configuration file for each module. 要禁用某个模块,请删除该节点或将其注释掉。To disable a module, delete the node or comment it out.

依赖项跟踪Dependency Tracking

依赖项跟踪收集有关应用对数据库以及外部服务和数据库的调用的遥测数据。Dependency tracking collects telemetry about calls your app makes to databases and external services and databases. 若要允许在 IIS 服务器中使用此模块,需要安装状态监视器To allow this module to work in an IIS server, you need to install Status Monitor.

还可以使用 TrackDependency API 编写自己的依赖项跟踪代码。You can also write your own dependency tracking code using the TrackDependency API.

依赖项可以自动收集,不需使用基于代理(无代码)的附加来修改代码。Dependencies can be auto-collected without modifying your code by using agent-based (codeless) attach. 若要在 Azure Web 应用中使用此模块,请启用 Application Insights 扩展To use it in Azure web apps, enable the Application Insights extension. 若要在 Azure VM 或 Azure 虚拟机规模集中使用它,请启用用于 VM 和虚拟机规模集的应用程序监视扩展To use it in Azure VM or Azure virtual machine scale set enable the Application Monitoring extension for VM and virtual machine scale set.

性能收集器Performance collector

收集系统性能计数器,例如 IIS 安装中的 CPU、内存和网络负载。Collects system performance counters such as CPU, memory, and network load from IIS installations. 可以指定要收集哪些计数器,包括自己设置的性能计数器。You can specify which counters to collect, including performance counters you have set up yourself.

Application Insights 诊断遥测Application Insights Diagnostics Telemetry

DiagnosticsTelemetryModule 报告 Application Insights 检测代码本身中的错误。The DiagnosticsTelemetryModule reports errors in the Application Insights instrumentation code itself. 例如,代码无法访问性能计数器,或 ITelemetryInitializer 引发异常。For example, if the code cannot access performance counters or if an ITelemetryInitializer throws an exception. 此模块跟踪的跟踪遥测数据将显示在诊断搜索中。Trace telemetry tracked by this module appears in the Diagnostic Search.

* `Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule`
* [Microsoft.ApplicationInsights](https://www.nuget.org/packages/Microsoft.ApplicationInsights) NuGet package. If you only install this package, the ApplicationInsights.config file is not automatically created.

开发人员模式Developer Mode

将调试器附加到应用程序进程后,DeveloperModeWithDebuggerAttachedTelemetryModule 强制 TelemetryChannel 立即发送数据,一次发送一个遥测项。DeveloperModeWithDebuggerAttachedTelemetryModule forces the Application Insights TelemetryChannel to send data immediately, one telemetry item at a time, when a debugger is attached to the application process. 这可以减少应用程序跟踪遥测数据与在 Application Insights 门户显示遥测数据的间隔时间,This reduces the amount of time between the moment when your application tracks telemetry and when it appears on the Application Insights portal. 但会明显增大 CPU 和网络带宽的开销。It causes significant overhead in CPU and network bandwidth.

Web 请求跟踪Web Request Tracking

报告 HTTP 请求的响应时间和结果代码Reports the response time and result code of HTTP requests.

异常跟踪Exception tracking

ExceptionTrackingTelemetryModule 跟踪 Web 应用中未经处理的异常。ExceptionTrackingTelemetryModule tracks unhandled exceptions in your web app. 请参阅故障和异常See Failures and exceptions.

  • Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule
  • Microsoft.ApplicationInsights.Web NuGet 包Microsoft.ApplicationInsights.Web NuGet package
  • Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule - 跟踪未观察到的任务异常Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule - tracks unobserved task exceptions
  • Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule - 跟踪辅助角色、Windows 服务和控制台应用程序的未经处理的异常。Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule - tracks unhandled exceptions for worker roles, windows services, and console applications.
  • Application Insights Windows Server NuGet 包。Application Insights Windows Server NuGet package.

EventSource 跟踪EventSource Tracking

通过 EventSourceTelemetryModule 可配置要作为跟踪发送到 Application Insights 的 EventSource 事件。EventSourceTelemetryModule allows you to configure EventSource events to be sent to Application Insights as traces. 有关跟踪 EventSource 事件的信息,请参阅使用 EventSource 事件For information on tracking EventSource events, see Using EventSource Events.

ETW 事件跟踪ETW Event Tracking

通过 EtwCollectorTelemetryModule 可从 ETW 提供程序配置要作为跟踪发送到 Application Insights 的事件。EtwCollectorTelemetryModule allows you to configure events from ETW providers to be sent to Application Insights as traces. 有关跟踪 ETW 事件的信息,请参阅使用 ETW 事件For information on tracking ETW events, see Using ETW Events.


Microsoft.ApplicationInsights 包提供 SDK 的核心 APIThe Microsoft.ApplicationInsights package provides the core API of the SDK. 其他遥测模块使用此包,也可以使用它来定义自己的遥测The other Telemetry Modules use this, and you can also use it to define your own telemetry.

  • ApplicationInsights.config 中没有条目。No entry in ApplicationInsights.config.
  • Microsoft.ApplicationInsights NuGet 包。Microsoft.ApplicationInsights NuGet package. 如果只安装此 NuGet,则不会生成任何 .config 文件。If you just install this NuGet, no .config file is generated.

遥测通道Telemetry Channel

遥测通道管理遥测到 Application Insights 服务的缓冲和传输。The telemetry channel manages buffering and transmission of telemetry to the Application Insights service.

  • Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel 是 Web 应用程序的默认通道。Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel is the default channel for web applications. 它在内存中缓冲数据,并采用重试机制和本地磁盘存储,以实现更可靠的遥测传输。It buffers data in memory, and employs retry mechanisms and local disk storage for more reliable telemetry delivery.
  • Microsoft.ApplicationInsights.InMemoryChannel 是一个轻型遥测通道,在未配置其他通道时使用。Microsoft.ApplicationInsights.InMemoryChannel is a lightweight telemetry channel, which is used if no other channel is configured.

遥测初始值设定项 (ASP.NET)Telemetry Initializers (ASP.NET)

遥测初始值设定项设置连同每个遥测项一起发送的上下文属性。Telemetry Initializers set context properties that are sent along with every item of telemetry.

可以编写自己的初始值设定项来设置上下文属性。You can write your own initializers to set context properties.

标准的初始值设定项由 Web 或 WindowsServer NuGet 包设置:The standard initializers are all set either by the Web or WindowsServer NuGet packages:

  • AccountIdTelemetryInitializer 设置 AccountId 属性。AccountIdTelemetryInitializer sets the AccountId property.

  • AuthenticatedUserIdTelemetryInitializer 像 JavaScript SDK 一样设置 AuthenticatedUserId 属性。AuthenticatedUserIdTelemetryInitializer sets the AuthenticatedUserId property as set by the JavaScript SDK.

  • 对于包含从 Azure 运行时环境提取的信息的所有遥测项,AzureRoleEnvironmentTelemetryInitializer 将更新 Device 上下文的 RoleNameRoleInstance 属性。AzureRoleEnvironmentTelemetryInitializer updates the RoleName and RoleInstance properties of the Device context for all telemetry items with information extracted from the Azure runtime environment.

  • 对于包含从 MS 版本生成的 BuildInfo.config 文件提取的值的所有遥测项,BuildInfoConfigComponentVersionTelemetryInitializer 将更新 Component 上下文的 Version 属性。BuildInfoConfigComponentVersionTelemetryInitializer updates the Version property of the Component context for all telemetry items with the value extracted from the BuildInfo.config file produced by MS Build.

  • ClientIpHeaderTelemetryInitializer 根据请求的 X-Forwarded-For HTTP 标头更新所有遥测项的 Location 上下文的 Ip 属性。ClientIpHeaderTelemetryInitializer updates Ip property of the Location context of all telemetry items based on the X-Forwarded-For HTTP header of the request.

  • DeviceTelemetryInitializer 更新所有遥测项的 Device 上下文的以下属性。DeviceTelemetryInitializer updates the following properties of the Device context for all telemetry items.

    • Type 设置为“PC”Type is set to "PC"
    • Id 设置为 Web 应用程序运行所在的计算机的域名。Id is set to the domain name of the computer where the web application is running.
    • OemName 设置为使用 WMI 从 Win32_ComputerSystem.Manufacturer 字段提取的值。OemName is set to the value extracted from the Win32_ComputerSystem.Manufacturer field using WMI.
    • Model 设置为使用 WMI 从 Win32_ComputerSystem.Model 字段提取的值。Model is set to the value extracted from the Win32_ComputerSystem.Model field using WMI.
    • NetworkType 设置为从 NetworkInterface 字段提取的值。NetworkType is set to the value extracted from the NetworkInterface.
    • Language 设置为 CurrentCulture 的名称。Language is set to the name of the CurrentCulture.
  • 对于包含 Web 应用程序运行所在计算机的域名的所有遥测项,DomainNameRoleInstanceTelemetryInitializer 将更新 Device 上下文的 RoleInstance 属性。DomainNameRoleInstanceTelemetryInitializer updates the RoleInstance property of the Device context for all telemetry items with the domain name of the computer where the web application is running.

  • OperationNameTelemetryInitializer 根据 HTTP 方法、ASP.NET MVC 控制器的名称以及为了处理请求而调用的操作,更新所有遥测项的 RequestTelemetryName 属性,以及 Operation 上下文的 Name 属性。OperationNameTelemetryInitializer updates the Name property of the RequestTelemetry and the Name property of the Operation context of all telemetry items based on the HTTP method, as well as names of ASP.NET MVC controller and action invoked to process the request.

  • OperationIdTelemetryInitializerOperationCorrelationTelemetryInitializer 在处理包含自动生成的 RequestTelemetry.Id 的请求时,更新跟踪的所有遥测项的 Operation.Id 上下文属性。OperationIdTelemetryInitializer or OperationCorrelationTelemetryInitializer updates the Operation.Id context property of all telemetry items tracked while handling a request with the automatically generated RequestTelemetry.Id.

  • 对于包含从用户浏览器中运行的 Application Insights JavaScript 检测代码生成的 ai_session Cookie 提取的值的所有遥测项,SessionTelemetryInitializer 将更新 Session 上下文的 Id 属性。SessionTelemetryInitializer updates the Id property of the Session context for all telemetry items with value extracted from the ai_session cookie generated by the ApplicationInsights JavaScript instrumentation code running in the user's browser.

  • SyntheticTelemetryInitializerSyntheticUserAgentTelemetryInitializer 在处理来自综合源(例如可用性测试或搜索引擎 Bot)的请求时,更新跟踪的所有遥测项的 UserSessionOperation 上下文属性。SyntheticTelemetryInitializer or SyntheticUserAgentTelemetryInitializer updates the User, Session, and Operation contexts properties of all telemetry items tracked when handling a request from a synthetic source, such as an availability test or search engine bot. 默认情况下,指标资源管理器不显示综合遥测数据。By default, Metrics Explorer does not display synthetic telemetry.

    <Filters> 设置请求的标识属性。The <Filters> set identifying properties of the requests.

  • 对于包含从用户浏览器中运行的 Application Insights JavaScript 检测代码生成的 ai_user Cookie 提取的值的所有遥测项,UserTelemetryInitializer 将更新 User 上下文的 IdAcquisitionDate 属性。UserTelemetryInitializer updates the Id and AcquisitionDate properties of User context for all telemetry items with values extracted from the ai_user cookie generated by the Application Insights JavaScript instrumentation code running in the user's browser.

  • WebTestTelemetryInitializer 设置用户 ID、会话 ID,以及来自可用性测试的 HTTP 请求的综合源属性。WebTestTelemetryInitializer sets the user ID, session ID, and synthetic source properties for HTTP requests that come from availability tests. <Filters> 设置请求的标识属性。The <Filters> set identifying properties of the requests.

对于在 Service Fabric 中运行的 .NET 应用程序,可包含 Microsoft.ApplicationInsights.ServiceFabric NuGet 包。For .NET applications running in Service Fabric, you can include the Microsoft.ApplicationInsights.ServiceFabric NuGet package. 该包所含的 FabricTelemetryInitializer 会将 Service Fabric 属性添加到遥测项。This package includes a FabricTelemetryInitializer, which adds Service Fabric properties to telemetry items. 有关详细信息,请参阅GitHub 页,了解由此 NuGet 包所添加的属性。For more information, see the GitHub page about the properties added by this NuGet package.

遥测处理器 (ASP.NET)Telemetry Processors (ASP.NET)

将遥测数据从 SDK 发送到门户之前,遥测处理器可以筛选和修改每个遥测项。Telemetry Processors can filter and modify each telemetry item just before it is sent from the SDK to the portal.

可以编写自己的遥测处理器You can write your own Telemetry Processors.

自适性采样遥测处理器(从 2.0.0-beta3 开始)Adaptive sampling Telemetry Processor (from 2.0.0-beta3)

此项已默认启用。This is enabled by default. 如果应用程序要发送大量遥测数据,此处理器将删除某些遥测数据。If your app sends a lot of telemetry, this processor removes some of it.

      <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">

参数将提供算法尝试实现的目标。The parameter provides the target that the algorithm tries to achieve. 每个 SDK 实例独立工作,因此,如果服务器是由多个计算机组成的群集,实际遥测量会相应地倍增。Each instance of the SDK works independently, so if your server is a cluster of several machines, the actual volume of telemetry will be multiplied accordingly.

了解有关采样的详细信息Learn more about sampling.

固定速率采样遥测处理器(从 2.0.0-beta1 开始)Fixed-rate sampling Telemetry Processor (from 2.0.0-beta1)

还有一种标准的采样遥测处理器(从 2.0.1 开始):There is also a standard sampling Telemetry Processor (from 2.0.1):

     <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.SamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">

     <!-- Set a percentage close to 100/N where N is an integer. -->
     <!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) -->


确定显示数据的 Application Insights 资源。This determines the Application Insights resource in which your data appears. 通常,我们会使用单独的密钥为每个应用程序单独创建一个资源。Typically you create a separate resource, with a separate key, for each of your applications.

如果想要以动态方式设置密钥(例如,要将应用程序的结果发送到不同的资源),可以在配置文件中省略密钥,并在代码中设置密钥。If you want to set the key dynamically - for example if you want to send results from your application to different resources - you can omit the key from the configuration file, and set it in code instead.

若要为 TelemetryClient 的所有实例(包括标准遥测模块)设置密钥,To set the key for all instances of TelemetryClient, including standard Telemetry Modules. 请在初始化方法中执行此操作,例如通过 ASP.NET 服务中的 global.aspx.cs:Do this in an initialization method, such as global.aspx.cs in an ASP.NET service:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;

    protected void Application_Start()
        TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
        configuration.InstrumentationKey = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
        var telemetryClient = new TelemetryClient(configuration);

如果只想将特定的一组事件发送到不同的资源,可以针对特定的 TelemetryClient 设置密钥:If you just want to send a specific set of events to a different resource, you can set the key for a specific TelemetryClient:

    var tc = new TelemetryClient();
    tc.Context.InstrumentationKey = "----- my key ----";
    // ...

若要获取新密钥,请在 Application Insights 门户中创建新资源To get a new key, create a new resource in the Application Insights portal.

ApplicationId 提供程序ApplicationId Provider

从 v2.6.0 开始可用Available starting in v2.6.0

此提供程序的用途是根据检测密钥查找应用程序 ID。The purpose of this provider is to lookup an Application ID based on an Instrumentation Key. 应用程序 ID 包括在 RequestTelemetry 和 DependencyTelemetry 中并用来在门户中确定关联。The Application ID is included in RequestTelemetry and DependencyTelemetry and used to determine Correlation in the Portal.

这是通过在代码或配置中设置 TelemetryConfiguration.ApplicationIdProvider 来提供的。This is available by setting TelemetryConfiguration.ApplicationIdProvider either in code or in config.

接口:IApplicationIdProviderInterface: IApplicationIdProvider

public interface IApplicationIdProvider
    bool TryGetApplicationId(string instrumentationKey, out string applicationId);

我们在 Microsoft.ApplicationInsights SDK 中提供了两个实现:ApplicationInsightsApplicationIdProviderDictionaryApplicationIdProviderWe provide two implementations in the Microsoft.ApplicationInsights sdk: ApplicationInsightsApplicationIdProvider and DictionaryApplicationIdProvider.


这是围绕我们的配置文件 API 的一个包装器。This is a wrapper around our Profile API. 它将限制请求和缓存结果。It will throttle requests and cache results.

当安装 Microsoft.ApplicationInsights.DependencyCollectorMicrosoft.ApplicationInsights.Web 时此提供程序将添加到配置文件中This provider is added to your config file when you install either Microsoft.ApplicationInsights.DependencyCollector or Microsoft.ApplicationInsights.Web

此类有一个可选属性 ProfileQueryEndpointThis class has an optional property ProfileQueryEndpoint. 默认情况下,这设置为 https://dc.services.visualstudio.com/api/profiles/{0}/appIdBy default this is set to https://dc.services.visualstudio.com/api/profiles/{0}/appId. 如果需要为此配置来配置一个代理,建议为基址使用代理并包括“/api/profiles/{0}/appId”。If you need to configure a proxy for this configuration, we recommend proxying the base address and including "/api/profiles/{0}/appId". 注意,“{0}”将在运行时根据请求替换为检测密钥。Note that '{0}' is substituted at runtime per request with the Instrumentation Key.

通过 ApplicationInsights.config 实现的示例配置:Example Configuration via ApplicationInsights.config:

    <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights">

通过代码实现的示例配置:Example Configuration via code:

TelemetryConfiguration.Active.ApplicationIdProvider = new ApplicationInsightsApplicationIdProvider();


这是一个静态提供程序,将依赖于所配置的检测密钥/应用程序 ID 对。This is a static provider, which will rely on your configured Instrumentation Key / Application ID pairs.

此类有一个 Defined 属性,它是包含检测密钥和应用程序 ID 对的一个 Dictionary<string,string>。This class has a property Defined, which is a Dictionary<string,string> of Instrumentation Key to Application ID pairs.

此类有一个可选的 Next 属性,这可以用来配置当请求你的配置中不存在的检测密钥时要使用的其他提供程序。This class has an optional property Next which can be used to configure another provider to use when an Instrumentation Key is requested that does not exist in your configuration.

通过 ApplicationInsights.config 实现的示例配置:Example Configuration via ApplicationInsights.config:

    <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.DictionaryApplicationIdProvider, Microsoft.ApplicationInsights">
            <Type key="InstrumentationKey_1" value="ApplicationId_1"/>
            <Type key="InstrumentationKey_2" value="ApplicationId_2"/>
        <Next Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />

通过代码实现的示例配置:Example Configuration via code:

TelemetryConfiguration.Active.ApplicationIdProvider = new DictionaryApplicationIdProvider{
 Defined = new Dictionary<string, string>
        {"InstrumentationKey_1", "ApplicationId_1"},
        {"InstrumentationKey_2", "ApplicationId_2"}

后续步骤Next steps

详细了解 APILearn more about the API.