Condividi tramite


Configurare Application Insights per un sito Web ASP.NET

Questa procedura consente di configurare un'app Web ASP.NET per l'invio di dati di telemetria alla funzionalità Application Insights del servizio Monitoraggio di Azure. È valida per le app ASP.NET ospitate nel server IIS locale o nel cloud.

Nota

La documentazione seguente si basa sull'API classica di Application Insights. Il piano a lungo termine per Application Insights prevede la raccolta di dati con OpenTelemetry. Per altre informazioni, vedere Abilitare OpenTelemetry di Monitoraggio di Azure per le applicazioni .NET, Node.js, Python e Java e la roadmap OpenTelemetry. Le indicazioni sulla migrazione sono disponibili per .NET, Node.js e Python.

Nota

Il 31 marzo 2025, il supporto per l'inserimento delle chiavi di strumentazione terminerà. L'inserimento delle chiavi di strumentazione continuerà a funzionare, ma non saranno più garantiti aggiornamenti o supporto per la funzionalità. Eseguire la transizione alle stringhe di connessione per sfruttare le nuove funzionalità.

Prerequisiti

Per aggiungere Application Insights a un sito Web ASP.NET, è necessario:

Importante

È consigliabile usare le stringhe di connessione anziché le chiavi di strumentazione. Le nuove aree di Azure richiedono l'uso di stringhe di connessione anziché di chiavi di strumentazione.

Una stringa di connessione identifica la risorsa a cui si vogliono associare i dati di telemetria. Consente inoltre di modificare gli endpoint che la risorsa userà come destinazione per la telemetria. Sarà necessario copiare la stringa di connessione e aggiungerla al codice dell'applicazione o alla variabile di ambiente "APPLICATIONINSIGHTS_CONNECTION_STRING".

Creare un'app Web ASP.NET di base

  1. Aprire Visual Studio 2019.
  2. Selezionare File>New (Nuovo) >Project (Progetto).
  3. Selezionare Applicazione Web ASP.NET (.NET Framework) C#.
  4. Immettere un nome di progetto e quindi selezionare Crea.
  5. Selezionare MVC>Crea.

Aggiungere automaticamente Application Insights

Questa sezione illustra l'aggiunta automatica di Application Insights a un'app Web ASP.NET basata su modello. Dall'interno del progetto di app Web ASP.NET in Visual Studio:

  1. Selezionare Progetto>Aggiungi Application Insights Telemetry>Application Insights SDK (locale)>Avanti>Fine>Chiudi.

  2. Aprire il file ApplicationInsights.config.

  3. Prima del tag di chiusura </ApplicationInsights> aggiungere una riga contenente la stringa di connessione per la risorsa di Application Insights. Trovare la stringa di connessione nel riquadro di panoramica della risorsa di Application Insights appena creata.

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  4. Selezionare Progetto>Gestisci pacchetti NuGet>Aggiornamenti. Aggiornare quindi ogni pacchetto NuGet Microsoft.ApplicationInsights all'ultima versione stabile.

  5. Eseguire l'applicazione selezionando IIS Express. Viene aperta un'app ASP.NET di base. Mentre si esplorano le pagine del sito, i dati di telemetria vengono inviati ad Application Insights.

Aggiungere Application Insights manualmente

Questa sezione illustra l'aggiunta manuale di Application Insights a un'app Web ASP.NET basata su modello. Questa sezione presuppone che si stia usando un'app Web basata sul modello di app Web MVC standard per il framework ASP.NET.

  1. Aggiungere i pacchetti NuGet seguenti e le relative dipendenze al progetto:

  2. In alcuni casi, il file ApplicationInsights.config viene creato automaticamente. Se il file è già presente, andare al passaggio 4.

    Se non viene creato automaticamente, è necessario crearlo manualmente. Nella directory radice di un'applicazione ASP.NET creare un nuovo file denominato ApplicationInsights.config.

  3. Copiare la configurazione XML seguente nel file appena creato:

    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
      <TelemetryInitializers>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
          <!-- Extended list of bots:
                search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
          <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
      </TelemetryInitializers>
      <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
          <ExcludeComponentCorrelationHttpHeadersOnDomains>
            <!-- 
            Requests to the following hostnames will not be modified by adding correlation headers.         
            Add entries here to exclude additional hostnames.
            NOTE: this configuration will be lost upon NuGet upgrade.
            -->
            <Add>core.windows.net</Add>
            <Add>core.chinacloudapi.cn</Add>
            <Add>core.cloudapi.de</Add>
            <Add>core.usgovcloudapi.net</Add>
          </ExcludeComponentCorrelationHttpHeadersOnDomains>
          <IncludeDiagnosticSourceActivities>
            <Add>Microsoft.Azure.EventHubs</Add>
            <Add>Azure.Messaging.ServiceBus</Add>
          </IncludeDiagnosticSourceActivities>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
          <!--
          Use the following syntax here to collect additional performance counters:
    
          <Counters>
            <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
            ...
          </Counters>
    
          PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
    
          NOTE: performance counters configuration will be lost upon NuGet upgrade.
    
          The following placeholders are supported as InstanceName:
            ??APP_WIN32_PROC?? - instance name of the application process  for Win32 counters.
            ??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
            ??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
          <!--
          Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider 
          with the following syntax:
    
          <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
            <ExcludedHeartbeatProperties>
              <Add>osType</Add>
              <Add>location</Add>
              <Add>name</Add>
              <Add>offer</Add>
              <Add>platformFaultDomain</Add>
              <Add>platformUpdateDomain</Add>
              <Add>publisher</Add>
              <Add>sku</Add>
              <Add>version</Add>
              <Add>vmId</Add>
              <Add>vmSize</Add>
              <Add>subscriptionId</Add>
              <Add>resourceGroupName</Add>
              <Add>placementGroupId</Add>
              <Add>tags</Add>
              <Add>vmScaleSetName</Add>
            </ExcludedHeartbeatProperties>
          </Add>
    
          NOTE: exclusions will be lost upon upgrade.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
          <!--</Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
          <Handlers>
            <!-- 
            Add entries here to filter out additional handlers: 
    
            NOTE: handler configuration will be lost upon NuGet upgrade.
            -->
            <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
            <Add>System.Web.StaticFileHandler</Add>
            <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
            <Add>System.Web.Optimization.BundleHandler</Add>
            <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
            <Add>System.Web.Handlers.TraceHandler</Add>
            <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
            <Add>System.Web.HttpDebugHandler</Add>
          </Handlers>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
      </TelemetryModules>
      <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
      <TelemetrySinks>
        <Add Name="default">
          <TelemetryProcessors>
            <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
            <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
            <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
              <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
              <ExcludedTypes>Event</ExcludedTypes>
            </Add>
            <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
              <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
              <IncludedTypes>Event</IncludedTypes>
            </Add>
            <!--
              Adjust the include and exclude examples to specify the desired semicolon-delimited types. (Dependency, Event, Exception, PageView, Request, Trace)
            -->
          </TelemetryProcessors>
          <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
        </Add>
      </TelemetrySinks>
      <!-- 
        Learn more about Application Insights configuration with ApplicationInsights.config here: 
        http://go.microsoft.com/fwlink/?LinkID=513840
      -->
      <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    </ApplicationInsights>
    
  4. Prima del tag di chiusura </ApplicationInsights> aggiungere la stringa di connessione per la risorsa di Application Insights. È possibile trovare la stringa di connessione nel riquadro di panoramica della risorsa di Application Insights appena creata.

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  5. Allo stesso livello del progetto del file ApplicationInsights.config, creare una cartella denominata ErrorHandler con un nuovo file C# denominato AiHandleErrorAttribute.cs. Il contenuto del file sarà simile al seguente:

    using System;
    using System.Web.Mvc;
    using Microsoft.ApplicationInsights;
    
    namespace WebApplication10.ErrorHandler //namespace will vary based on your project name
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
        public class AiHandleErrorAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
                {
                    //If customError is Off, then AI HTTPModule will report the exception
                    if (filterContext.HttpContext.IsCustomErrorEnabled)
                    {   
                        var ai = new TelemetryClient();
                        ai.TrackException(filterContext.Exception);
                    } 
                }
                base.OnException(filterContext);
            }
        }
    }
    
  6. Nella cartella App_Start aprire il file FilterConfig.cs e modificarlo in modo che corrisponda all'esempio:

    using System.Web;
    using System.Web.Mvc;
    
    namespace WebApplication10 //Namespace will vary based on project name
    {
        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());
            }
        }
    }
    
  7. Se Web.config è già aggiornato, ignorare questo passaggio. In caso contrario, aggiornare il file come segue:

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      https://go.microsoft.com/fwlink/?LinkId=301880
      -->
    <configuration>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2" />
        <!-- Code added for Application Insights start -->
        <httpModules>
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
        <!-- Code added for Application Insights end -->
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
            <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
          <!-- Code added for Application Insights start -->
          <dependentAssembly>
            <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
          </dependentAssembly>
          <!-- Code added for Application Insights end -->
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <!-- Code added for Application Insights start -->
        <modules>
          <remove name="TelemetryCorrelationHttpModule" />
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler" />
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
        <!-- Code added for Application Insights end -->
      </system.webServer>
    </configuration>
    
    

Il monitoraggio delle applicazioni sul lato server è stato configurato correttamente. Se si esegue l'app Web, i dati di telemetria inizieranno a comparire in Application Insights.

Aggiungere il monitoraggio sul lato client

Le sezioni precedenti forniscono indicazioni sui metodi per configurare automaticamente e manualmente il monitoraggio lato server. Per aggiungere il monitoraggio lato client, usare l'SDK JavaScript lato client. È possibile monitorare le transazioni lato client di qualsiasi pagina Web aggiungendo uno script di caricamento di JavaScript (Web) SDK prima del tag </head> di chiusura del codice HTML della pagina.

Sebbene sia possibile aggiungere manualmente lo script di caricamento di JavaScript (Web) SDK all'intestazione di ogni pagina HTML, è consigliabile aggiungerlo a una pagina primaria. Questa azione inserisce lo script di caricamento di JavaScript (Web) SDK in tutte le pagine di un sito.

Per l'app MVC ASP.NET basata su modello di questo articolo, il file da modificare è _Layout.cshtml. È possibile trovarlo in Visualizzazioni>Condivise. Per aggiungere il monitoraggio sul lato client, aprire _Layout.cshtml e seguire le istruzioni per l'installazione basata su script di caricamento di JavaScript (Web) SDK riportate nell'articolo sulla configurazione di JavaScript SDK sul lato client.

Metriche attive

È possibile usare le metriche attive per verificare rapidamente se il monitoraggio delle applicazioni con Application Insights è configurato correttamente. La visualizzazione dei dati di telemetria nel portale di Azure può richiedere alcuni minuti, ma il riquadro delle metriche attive mostra l'utilizzo della CPU del processo in esecuzione quasi in tempo reale. Può anche visualizzare altri dati di telemetria, ad esempio richieste, dipendenze e tracce.

Abilitare le metriche attive usando il codice per qualsiasi applicazione .NET

Nota

Le metriche attive sono abilitate per impostazione predefinita quando si esegue l'onboarding seguendo le istruzioni consigliate per le applicazioni .NET.

Per configurare manualmente le metriche attive:

  1. Installare il pacchetto NuGet Microsoft.ApplicationInsights.PerfCounterCollector.
  2. Il codice dell'app console di esempio seguente mostra la configurazione delle metriche attive:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using System;
using System.Threading.Tasks;

namespace LiveMetricsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a TelemetryConfiguration instance.
            TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
            config.InstrumentationKey = "INSTRUMENTATION-KEY-HERE";
            QuickPulseTelemetryProcessor quickPulseProcessor = null;
            config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
                .Use((next) =>
                {
                    quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
                    return quickPulseProcessor;
                })
                .Build();

            var quickPulseModule = new QuickPulseTelemetryModule();

            // Secure the control channel.
            // This is optional, but recommended.
            quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
            quickPulseModule.Initialize(config);
            quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);

            // Create a TelemetryClient instance. It is important
            // to use the same TelemetryConfiguration here as the one
            // used to set up live metrics.
            TelemetryClient client = new TelemetryClient(config);

            // This sample runs indefinitely. Replace with actual application logic.
            while (true)
            {
                // Send dependency and request telemetry.
                // These will be shown in live metrics.
                // CPU/Memory Performance counter is also shown
                // automatically without any additional steps.
                client.TrackDependency("My dependency", "target", "http://sample",
                    DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
                client.TrackRequest("My Request", DateTimeOffset.Now,
                    TimeSpan.FromMilliseconds(230), "200", true);
                Task.Delay(1000).Wait();
            }
        }
    }
}

L'esempio precedente riguarda un'app console, ma lo stesso codice può essere usato in qualsiasi applicazione .NET. Se sono abilitati altri moduli di telemetria per la raccolta automatica dei dati di telemetria, è importante assicurarsi che la stessa configurazione usata per l'inizializzazione di tali moduli venga usata per il modulo delle metriche attive.

Domande frequenti

Questa sezione fornisce le risposte alle domande comuni.

Qual è la procedura per disinstallare l'SDK?

Per rimuovere Application Insights, è necessario rimuovere i pacchetti NuGet e i riferimenti dall'API nell'applicazione. È possibile disinstallare i pacchetti NuGet usando Gestione pacchetti NuGet in Visual Studio.

  1. Se la raccolta delle tracce è abilitata, disinstallare prima di tutto il pacchetto Microsoft.ApplicationInsights.TraceListener usando Gestione pacchetti NuGet, ma non rimuovere alcuna dipendenza.
  2. Disinstallare il pacchetto Microsoft.ApplicationInsights.Web e rimuovere le dipendenze usando Gestione pacchetti NuGet e le relative opzioni di disinstallazione all'interno del controllo Opzioni di Gestione pacchetti NuGet.
  3. Per rimuovere completamente Application Insights, controllare ed eliminare manualmente il codice o i file aggiunti insieme alle chiamate API aggiunte nel progetto. Per altre informazioni, vedere Cosa viene creato quando si aggiunge Application Insights SDK?.

Cosa viene creato quando si aggiunge Application Insights SDK?

Quando si aggiunge Application Insights al progetto, vengono creati file e viene aggiunto codice ad alcuni dei file. Disinstallare solo i pacchetti NuGet non sempre consente di rimuovere i file e il codice. Per rimuovere completamente Application Insights, occorre controllare ed eliminare manualmente il codice o i file aggiunti insieme alle chiamate API aggiunte nel progetto.

Quando si aggiunge Application Insights Telemetry a un progetto ASP.NET di Visual Studio, vengono aggiunti i file seguenti:

  • ApplicationInsights.config
  • AiHandleErrorAttribute.cs

Vengono aggiunte le parti di codice seguenti:

  • [Nome del progetto].csproj

     <ApplicationInsightsResourceId>/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/Default-ApplicationInsights-EastUS/providers/microsoft.insights/components/WebApplication4</ApplicationInsightsResourceId>
    
  • Packages.config

    <packages>
    ...
    
      <package id="Microsoft.ApplicationInsights" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.Web" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.12.0" targetFramework="net472" />
    
      <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.7" targetFramework="net472" />
    
      <package id="System.Buffers" version="4.4.0" targetFramework="net472" />
      <package id="System.Diagnostics.DiagnosticSource" version="4.6.0" targetFramework="net472" />
      <package id="System.Memory" version="4.5.3" targetFramework="net472" />
      <package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net472" />
      <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
    ...
    </packages>
    
  • Layout.cshtml

    Se il progetto ha un file Layout.cshtml, viene aggiunto il codice seguente.

    <head>
    ...
        <script type = 'text/javascript' >
            var appInsights=window.appInsights||function(config)
            {
                function r(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} }
                var t = { config:config},u=document,e=window,o='script',s=u.createElement(o),i,f;for(s.src=config.url||'//az416426.vo.msecnd.net/scripts/a/ai.0.js',u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=['Event','Exception','Metric','PageView','Trace','Ajax'];i.length;)r('track'+i.pop());return r('setAuthenticatedUserContext'),r('clearAuthenticatedUserContext'),config.disableExceptionTracking||(i='onerror',r('_'+i),f=e[i],e[i]=function(config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o),s}),t
            }({
                instrumentationKey:'00000000-0000-0000-0000-000000000000'
            });
    
            window.appInsights=appInsights;
            appInsights.trackPageView();
        </script>
    ...
    </head>
    
  • ConnectedService.json

    {
      "ProviderId": "Microsoft.ApplicationInsights.ConnectedService.ConnectedServiceProvider",
      "Version": "16.0.0.0",
      "GettingStartedDocument": {
        "Uri": "https://go.microsoft.com/fwlink/?LinkID=613413"
      }
    }
    
  • FilterConfig.cs

            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());// This line was added
            }
    

Risoluzione dei problemi

Vedere l'articolo sulla risoluzione dei problemi dedicato.

C'è un problema noto nella versione corrente di Visual Studio 2019: l'archiviazione della chiave di strumentazione o della stringa di connessione in un segreto utente non funziona per le app basate su .NET Framework. La chiave deve essere hardcoded nel file applicationinsights.config per risolvere questo bug. Questo articolo è progettato per evitare completamente questo problema, non usando segreti utente.

Testare la connettività tra l'host dell'applicazione e il servizio di inserimento

Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento come chiamate REST agli endpoint di inserimento. È possibile testare la connettività dal server Web o dal computer host dell'applicazione agli endpoint del servizio di inserimento usando client REST non elaborati da comandi PowerShell o curl. Vedere Risolvere i problemi di dati di telemetria delle applicazioni mancanti in Application Insights per Monitoraggio di Azure.

SDK open source

Leggere e contribuire al codice.

Per gli aggiornamenti e le correzioni di bug più recenti, vedere le note sulla versione.

Note sulla versione

Per le versioni 2.12 e successive: SDK .NET (inclusi ASP.NET, ASP.NET Core e adattatori di registrazione)

Gli aggiornamenti del servizio riepilogano anche i principali miglioramenti di Application Insights.

Passaggi successivi