Application Insights voor .NET-consoletoepassingen

Waarschuwing

Gebruik het pakket Microsoft.ApplicationInsights.WorkerService en de bijbehorende instructies van Application Insights voor Worker Service-toepassingen (niet-HTTP-toepassingen) voor consoletoepassingen. Het is compatibel met LTS-versies (Long Term Support) van .NET Core en .NET Framework of hoger.

Met Application Insights kunt u uw webtoepassing controleren op beschikbaarheid, prestaties en gebruik.

Aan de slag

  • Maak in de Azure Portal een Application Insights-resource.

  • Neem een kopie van de connection string. Zoek de connection string in de vervolgkeuzelijst Essentials van de nieuwe resource die u hebt gemaakt.

  • Installeer het nieuwste Microsoft.ApplicationInsights-pakket .

  • Stel de connection string in uw code in voordat u telemetrie bijhoudt (of de omgevingsvariabele APPLICATIONINSIGHTS_CONNECTION_STRING instelt). Daarna moet u de telemetrie handmatig kunnen bijhouden en zien in de Azure Portal.

    // 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!");
    

    Notitie

    Telemetrie wordt niet direct verzonden. Items worden in batches uitgevoerd en verzonden door de ApplicationInsights SDK. Console-apps worden afgesloten na het aanroepen van Track() methoden.

    Telemetrie wordt mogelijk niet verzonden, tenzij Flush() enDelaySleep/worden uitgevoerd voordat de app wordt afgesloten, zoals wordt weergegeven in het volledige voorbeeld verderop in dit artikel. Sleep is niet vereist als u gebruikt InMemoryChannel.

  • Installeer de nieuwste versie van het pakket Microsoft.ApplicationInsights.DependencyCollector . Http, SQL of andere externe afhankelijkheidsaanroepen worden automatisch bijgehouden.

U kunt Application Insights initialiseren en configureren vanuit de code of met behulp van ApplicationInsights.config het bestand. Zorg ervoor dat de initialisatie zo vroeg mogelijk plaatsvindt.

Notitie

ApplicationInsights.config wordt niet ondersteund door .NET Core-toepassingen.

Het configuratiebestand gebruiken

Voor .NET Framework-toepassingen zoekt de Application Insights SDK standaard naar het ApplicationInsights.config bestand in de werkmap wanneer TelemetryConfiguration het wordt gemaakt. Het lezen van het configuratiebestand wordt niet ondersteund in .NET Core.

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

U kunt ook een pad naar het configuratiebestand opgeven:

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

U kunt een volledig voorbeeld van het configuratiebestand krijgen door de nieuwste versie van het pakket Microsoft.ApplicationInsights.WindowsServer te installeren. Dit is de minimale configuratie voor afhankelijkheidsverzameling die gelijk is aan het codevoorbeeld:

<?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>

Telemetrieverzameling configureren vanuit code

Notitie

Het lezen van het configuratiebestand wordt niet ondersteund in .NET Core.

  • Maak en configureer een exemplaar tijdens het opstarten van de DependencyTrackingTelemetryModule toepassing. Het moet singleton zijn en moet worden bewaard voor de levensduur van de toepassing.

    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);
    
  • Algemene initialisatiefuncties voor telemetrie toevoegen:

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

    Als u een configuratie hebt gemaakt met een gewone TelemetryConfiguration() constructor, moet u ook correlatieondersteuning inschakelen. Deze is niet nodig als u de configuratie leest uit een bestand of als u of TelemetryConfiguration.ActivegebruiktTelemetryConfiguration.CreateDefault().

    configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
    
  • Mogelijk wilt u ook de collectormodule prestatiemeteritems installeren en initialiseren, zoals beschreven op deze website.

Volledig voorbeeld

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