適用於 .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 為基礎的應用程式,根據預設,Application Insights SDK 會在建立 TelemetryConfiguration 時,於工作目錄中尋找 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;
        }
    }
}