适用于 .NET 控制台应用程序的 Application Insights

警告

使用适用于辅助角色服务应用程序的 Application Insights 的 Microsoft.ApplicationInsights.WorkerService 包和相关说明 , (控制台应用程序) 非 HTTP 应用程序。 它与长期支持 (LTS) 版本的 .NET Core 和 .NET Framework 或更高版本兼容。

使用 Application Insights 可以监视 Web 应用程序的可用性、性能和使用情况。

入门

  • Azure 门户,创建 Application Insights 资源。

  • 获取连接字符串的副本。 在创建的新资源的“概要”下拉列表中找到该连接字符串。

  • 安装最新的 Microsoft.ApplicationInsights 包。

  • 在跟踪任何遥测(或设置 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量)之前,在代码中设置连接字符串。 设置后,应能手动跟踪遥测并在 Azure 门户中查看。

    // You may use different options to create configuration as shown later in this article
    TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
    configuration.ConnectionString = <Copy connection string from Application Insights Resource Overview>;
    var telemetryClient = new TelemetryClient(configuration);
    telemetryClient.TrackTrace("Hello World!");
    

    注意

    遥测不会立即发送。 项由 ApplicationInsights SDK 以批处理方式发送。 调用 Track() 方法后控制台应用退出。

    除非在应用退出之前完成 Flush()Sleep/Delay,否则可能不会发送遥测,如本文后面的完整示例所示。 如果你使用 InMemoryChannel,则不需要 Sleep

  • 安装最新版本的 Microsoft.ApplicationInsights.DependencyCollector 包。 它会自动跟踪 HTTP、SQL 或其他一些外部依赖项调用。

可通过代码或使用 ApplicationInsights.config 文件初始化和配置 Application Insights。 请确保尽早进行初始化。

注意

.NET Core 应用程序不支持 ApplicationInsights.config。

使用配置文件

对于基于 .NET Framework 的应用程序,默认情况下,创建 TelemetryConfiguration 时,Application Insights SDK 将在工作目录中查找 ApplicationInsights.config 文件。 .NET Core 不支持读取配置文件。

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

还可以指定该配置文件的路径:

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

通过安装最新版本的 Microsoft.ApplicationInsights.WindowsServer 包,可以获取配置文件的完整示例。 此处是依赖项集合的“最小”配置,等效于代码示例:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <ConnectionString>"Copy connection string from Application Insights Resource Overview"</ConnectionString>
  <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>

通过代码配置遥测集合

注意

.NET Core 不支持读取配置文件。

  • 在应用程序启动期间,创建和配置 DependencyTrackingTelemetryModule 实例。 它必须是单一实例,并且必须在应用程序生命周期内保留。

    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");
    //...
    
    // 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);
    
  • 添加常用遥测初始值设定项:

    // ensures proper DependencyTelemetry.Type is set for Azure RESTful API calls
    configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
    

    如果使用纯 TelemetryConfiguration() 构造函数创建了配置,还需要启用关联支持。 如果你从文件中读取配置或使用了 TelemetryConfiguration.CreateDefault()TelemetryConfiguration.Active,则不需要。

    configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
    
  • 你可能还想安装和初始化性能计数器收集器模块,如本网站中所述。

完整示例

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.ConnectionString = "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();

            // Console apps should use the WorkerService package.
            // This uses ServerTelemetryChannel which does not have synchronous flushing.
            // For this reason we add a short 5s delay in this sample.
            
            Task.Delay(5000).Wait();

            // If you're using InMemoryChannel, Flush() is synchronous and the short delay is not required.

        }

        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;
        }
    }
}