适用于 .NET 控制台应用程序的 Application InsightsApplication Insights for .NET console applications

使用 Application Insights 可以监视 Web 应用程序的可用性、性能和使用情况。Application Insights lets you monitor your web application for availability, performance, and usage.

需要订阅 AzureYou need a subscription with Azure. 使用 Microsoft 帐户登录,该帐户可能适用于 Windows、Xbox Live 或其他 Azure 云服务。Sign in with a Microsoft account, which you might have for Windows, Xbox Live, or other Azure cloud services. 团队可能拥有 Azure 组织订阅:要求所有者使用 Microsoft 帐户你将加入其中。Your team might have an organizational subscription to Azure: ask the owner to add you to it using your Microsoft account.

备注

强烈建议将 Microsoft.ApplicationInsights.WorkerService 包以及此处的相关说明用于任何控制台应用程序。It is highly recommended to use the Microsoft.ApplicationInsights.WorkerService package and associated instructions from here for any Console Applications. 此包针对 NetStandard2.0,因此可在 .NET Core 2.1 或更高版本,以及 .NET Framework 4.7.2 或更高版本中使用。This package targets NetStandard2.0, and hence can be used in .NET Core 2.1 or higher, and .NET Framework 4.7.2 or higher.

入门Getting started

重要

新的 Azure 区域要求使用连接字符串而不是检测密钥。New Azure regions require the use of connection strings instead of instrumentation keys. 连接字符串用于标识要与遥测数据关联的资源。Connection string identifies the resource that you want to associate your telemetry data with. 它还允许你修改可供你的资源将其用作遥测目标的终结点。It also allows you to modify the endpoints your resource will use as a destination for your telemetry. 你需要复制连接字符串,并将其添加到应用程序的代码或环境变量中。You will need to copy the connection string and add it to your application's code or to an environment variable.

  • Azure 门户中,创建 Application Insights 资源In the Azure portal, create an Application Insights resource. 对于应用程序类型,选择“常规”。For application type, choose General.
  • 获取检测密钥的副本。Take a copy of the Instrumentation Key. 在创建的新资源的“概要”下拉列表中找到该密钥。Find the key in the Essentials drop-down of the new resource you created.
  • 安装最新的 Microsoft.ApplicationInsights 包。Install latest Microsoft.ApplicationInsights package.
  • 在跟踪任何遥测之前,请先在代码中设置检测密钥(或设置 APPINSIGHTS_INSTRUMENTATIONKEY 环境变量)。Set the instrumentation key in your code before tracking any telemetry (or set APPINSIGHTS_INSTRUMENTATIONKEY environment variable). 设置后,应能手动跟踪遥测并在 Azure 门户中查看After that, you should be able to manually track telemetry and see it on the Azure portal
// you may use different options to create configuration as shown later in this article
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = " *your key* ";
var telemetryClient = new TelemetryClient(configuration);
telemetryClient.TrackTrace("Hello World!");

备注

遥测不会立即发送。Telemetry is not sent instantly. 遥测项由 ApplicationInsights SDK 以批处理方式发送。Telemetry items are batched and sent by the ApplicationInsights SDK. 在控制台应用中(该应用在调用 Track() 方法后立即退出),可能不会发送遥测,除非在应用程序退出之前完成 Flush()Sleep/Delay,如后文中的完整示例所示。In Console apps, which exits right after calling Track() methods, telemetry may not be sent unless Flush() and Sleep/Delay is done before the app exits as shown in full example later in this article. 如果使用 InMemoryChannel,则 Sleep 不是必需的。Sleep is not required if you are using InMemoryChannel. 此处存在一个待解决的问题,涉及对 Sleep 的需求,可在此处跟踪该问题:ApplicationInsights-dotnet/issues/407There is an active issue regarding the need for Sleep which is tracked here: ApplicationInsights-dotnet/issues/407

可通过代码或 ApplicationInsights.config 文件初始化和配置 Application Insights。You may initialize and configure Application Insights from the code or using ApplicationInsights.config file. 请确保尽早进行初始化。Make sure initialization happens as early as possible.

备注

提到了 ApplicationInsights.config 的说明仅适用于以 .NET Framework 为目标的应用,不适用于 .NET Core 应用程序。Instructions referring to ApplicationInsights.config are only applicable to apps that are targeting the .NET Framework, and do not apply to .NET Core applications.

使用配置文件Using config file

默认情况下,创建 TelemetryConfiguration 时,Application Insights SDK 在工作目录中查找 ApplicationInsights.config 文件By default, Application Insights SDK looks for ApplicationInsights.config file in the working directory when TelemetryConfiguration is being created

TelemetryConfiguration config = TelemetryConfiguration.Active; // Reads ApplicationInsights.config file if present

还可以指定该配置文件的路径。You may also specify path to the config file.

using System.IO;
TelemetryConfiguration configuration = TelemetryConfiguration.CreateFromConfiguration(File.ReadAllText("C:\\ApplicationInsights.config"));
var telemetryClient = new TelemetryClient(configuration);

有关详细信息,请参阅配置文件参考For more information, see configuration file reference.

通过安装最新版本的 Microsoft.ApplicationInsights.WindowsServer 包,可以获取配置文件的完整示例。You may get a full example of the config file by installing latest version of Microsoft.ApplicationInsights.WindowsServer package. 此处是依赖项集合的“最小”配置,等效于代码示例。Here is the minimal configuration for dependency collection that is equivalent to the code example.

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <InstrumentationKey>Your Key</InstrumentationKey>
  <TelemetryInitializers>
    <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector"/>
  </TelemetryInitializers>
  <TelemetryModules>
    <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
      <ExcludeComponentCorrelationHttpHeadersOnDomains>
        <Add>core.windows.net</Add>
        <Add>core.chinacloudapi.cn</Add>
        <Add>core.cloudapi.de</Add>
        <Add>core.usgovcloudapi.net</Add>
        <Add>localhost</Add>
        <Add>127.0.0.1</Add>
      </ExcludeComponentCorrelationHttpHeadersOnDomains>
      <IncludeDiagnosticSourceActivities>
        <Add>Microsoft.Azure.ServiceBus</Add>
        <Add>Microsoft.Azure.EventHubs</Add>
      </IncludeDiagnosticSourceActivities>
    </Add>
  </TelemetryModules>
  <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
</ApplicationInsights>

通过代码配置遥测集合Configuring telemetry collection from code

备注

.NET Core 不支持读取配置文件。Reading config file is not supported on .NET Core. 可以考虑使用 Application Insights SDK for ASP.NET CoreYou may consider using Application Insights SDK for ASP.NET Core

  • 在应用程序启动期间创建并配置 DependencyTrackingTelemetryModule 实例 - 该实例必须是单一实例,并在应用程序生存期中保留。During application start-up create and configure DependencyTrackingTelemetryModule instance - it must be singleton and must be preserved for application lifetime.
var module = new DependencyTrackingTelemetryModule();

// prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
//...

// enable known dependency tracking, note that in future versions, we will extend this list. 
// please check default settings in https://github.com/Microsoft/ApplicationInsights-dotnet-server/blob/develop/Src/DependencyCollector/DependencyCollector/ApplicationInsights.config.install.xdt

module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");
//....

// initialize the module
module.Initialize(configuration);
  • 添加常用遥测初始值设定项Add common telemetry initializers
// ensures proper DependencyTelemetry.Type is set for Azure RESTful API calls
configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

如果使用纯 TelemetryConfiguration() 构造函数创建了配置,还需要启用关联支持。If you created configuration with plain TelemetryConfiguration() constructor, you need to enable correlation support additionally. 如果从文件中读取配置(使用 TelemetryConfiguration.CreateDefault()TelemetryConfiguration.Active),则不需要。It is not needed if you read configuration from file, used TelemetryConfiguration.CreateDefault() or TelemetryConfiguration.Active.

configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
  • 你可能还希望安装和初始化性能计数器收集器模块,如此处所述You may also want to install and initialize Performance Counter collector module as described here

完整示例Full example

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();

            configuration.InstrumentationKey = "removed";
            configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

            var telemetryClient = new TelemetryClient(configuration);
            using (InitializeDependencyTracking(configuration))
            {
                // run app...

                telemetryClient.TrackTrace("Hello World!");

                using (var httpClient = new HttpClient())
                {
                    // Http dependency is automatically tracked!
                    httpClient.GetAsync("https://microsoft.com").Wait();
                }

            }

            // before exit, flush the remaining data
            telemetryClient.Flush();

            // flush is not blocking when not using InMemoryChannel so wait a bit. There is an active issue regarding the need for `Sleep`/`Delay`
            // which is tracked here: https://github.com/microsoft/ApplicationInsights-dotnet/issues/407
            Task.Delay(5000).Wait();

        }

        static DependencyTrackingTelemetryModule InitializeDependencyTracking(TelemetryConfiguration configuration)
        {
            var module = new DependencyTrackingTelemetryModule();

            // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("localhost");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");

            // enable known dependency tracking, note that in future versions, we will extend this list. 
            // please check default settings in https://github.com/microsoft/ApplicationInsights-dotnet-server/blob/develop/WEB/Src/DependencyCollector/DependencyCollector/ApplicationInsights.config.install.xdt

            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

            // initialize the module
            module.Initialize(configuration);

            return module;
        }
    }
}

后续步骤Next steps

  • 监视依赖项,查看 REST、SQL 或其他外部资源是否会降低性能。Monitor dependencies to see if REST, SQL, or other external resources are slowing you down.
  • 使用 API,发送自己的事件和指标以获取应用的性能和使用情况的更详细视图。Use the API to send your own events and metrics for a more detailed view of your app's performance and usage.