A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/azure/application-insights/app-insights-asp-net-core below:

Configure monitoring for ASP.NET and ASP.NET Core with Application Insights - Azure Monitor

This article describes how to enable and configure Application Insights for ASP.NET and ASP.NET Core applications. This procedure configures your application to send telemetry to Application Insights.

Application Insights can collect the following telemetry from your ASP.NET and ASP.NET Core applications:

Supported scenarios

Note

The Application Insights SDK for ASP.NET Core can monitor your applications no matter where or how they run. If your application is running and has network connectivity to Azure, telemetry can be collected. Application Insights monitoring is supported everywhere .NET Core is supported.

Supported ASP.NET ASP.NET Core Operating system Windows Windows, Linux, or Mac Hosting method In-process (IIS or IIS Express) In process or out of process Deployment method Web Deploy, MSI, or manual file copy Framework dependent or self-contained Web server Internet Information Services (IIS) Internet Information Server (IIS) or Kestrel Hosting platform Azure App Service (Windows), Azure Virtual Machines, or on-premises servers The Web Apps feature of Azure App Service, Azure Virtual Machines, Docker, and Azure Kubernetes Service (AKS) .NET version .NET Framework 4.6.1 and later All officially supported .NET versions that aren't in preview IDE Visual Studio Visual Studio, Visual Studio Code, or command line Prerequisites Create a basic web app

We use an MVC application example. If you're using the Worker Service, use the instructions in Application Insights for Worker Service applications.

  1. Open Visual Studio.
  2. Select Create a new project.
  3. Choose ASP.NET Web Application (.NET Framework) with C# and select Next.
  4. Enter a Project name, then select Create.
  5. Choose MVC, then select Create.
  1. Open Visual Studio.
  2. Select Create a new project.
  3. Choose ASP.NET Core Web App (Razor Pages) with C# and select Next.
  4. Enter a Project name, then select Create.
  5. Choose a Framework (LTS or STS), then select Create.
Add Application Insights automatically (Visual Studio)

This section guides you through automatically adding Application Insights to a template-based web app.

From within your ASP.NET web app project in Visual Studio:

  1. Select Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close.

  2. Open the ApplicationInsights.config file.

  3. Before the closing </ApplicationInsights> tag, add a line that contains the connection string for your Application Insights resource. Find your connection string on the overview pane of the newly created Application Insights resource.

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  4. Select Project > Manage NuGet Packages > Updates. Then update each Microsoft.ApplicationInsights NuGet package to the latest stable release.

  5. Run your application by selecting IIS Express. A basic ASP.NET app opens. As you browse through the pages on the site, telemetry is sent to Application Insights.

Note

For Visual Studio for Mac, use the manual guidance. Only the Windows version of Visual Studio supports this procedure.

From within your ASP.NET web app project in Visual Studio:

  1. Go to Project > Add Application Insights Telemetry.

  2. Select Azure Application Insights > Next.

  3. Choose your subscription and Application Insights instance. Or you can create a new instance with Create new. Select Next.

  4. Add or confirm your Application Insights connection string. It should be prepopulated based on your selection in the previous step. Select Finish.

  5. After you add Application Insights to your project, check to confirm that you're using the latest stable release of the SDK. Go to Project > Manage NuGet Packages > Microsoft.ApplicationInsights.AspNetCore. If you need to, select Update.

Add Application Insights manually (no Visual Studio)

This section guides you through manually adding Application Insights to a template-based web app.

  1. Add the following NuGet packages and their dependencies to your project:

  2. In some cases, the ApplicationInsights.config file is created for you automatically. If the file is already present, skip to step 4.

    Create it yourself if it's missing. In the root directory of an ASP.NET application, create a new file called ApplicationInsights.config.

  3. Copy the following XML configuration into your newly created file:

    <?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 the connection string from your Application Insights resource</ConnectionString>
    </ApplicationInsights>
    
  4. Add the connection string, which can be done in two ways:

  5. At the same level of your project as the ApplicationInsights.config file, create a folder called ErrorHandler with a new C# file called AiHandleErrorAttribute.cs. The contents of the file look like this:

    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. In the App_Start folder, open the FilterConfig.cs file and change it to match the sample:

    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. If Web.config is already updated, skip this step. Otherwise, update the file as follows:

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

At this point, you successfully configured server-side application monitoring. If you run your web app, you see telemetry begin to appear in Application Insights.

  1. Install the Application Insights SDK NuGet package for ASP.NET Core.

    We recommend that you always use the latest stable version. Find full release notes for the SDK on the open-source GitHub repo.

    The following code sample shows the changes to add to your project's .csproj file:

    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    </ItemGroup>
    
  2. Add AddApplicationInsightsTelemetry() to your program.cs class.

    Add builder.Services.AddApplicationInsightsTelemetry(); after the WebApplication.CreateBuilder() method, as in this example:

    // This method gets called by the runtime. Use this method to add services to the container.
    var builder = WebApplication.CreateBuilder(args);
    
    // The following line enables Application Insights telemetry collection.
    builder.Services.AddApplicationInsightsTelemetry();
    
    // This code adds other services for your application.
    builder.Services.AddMvc();
    
    var app = builder.Build();
    
  3. Add the connection string, which can be done in three ways:

User secrets and other configuration providers

If you want to store the connection string in ASP.NET Core user secrets or retrieve it from another configuration provider, you can use the overload with a Microsoft.Extensions.Configuration.IConfiguration parameter. An example parameter is services.AddApplicationInsightsTelemetry(Configuration);.

In Microsoft.ApplicationInsights.AspNetCore version 2.15.0 and later, calling services.AddApplicationInsightsTelemetry() automatically reads the connection string from Microsoft.Extensions.Configuration.IConfiguration of the application. There's no need to explicitly provide IConfiguration.

If IConfiguration has loaded configuration from multiple providers, then services.AddApplicationInsightsTelemetry prioritizes configuration from appsettings.json, irrespective of the order in which providers are added. Use the services.AddApplicationInsightsTelemetry(IConfiguration) method to read configuration from IConfiguration without this preferential treatment for appsettings.json.

Run your application

Run your application and make requests to it. Telemetry should now flow to Application Insights. The Application Insights SDK automatically collects incoming web requests to your application, along with the following telemetry.

Live metrics

Live metrics can be used to quickly verify if application monitoring with Application Insights is configured correctly. Telemetry can take a few minutes to appear in the Azure portal, but the live metrics pane shows CPU usage of the running process in near real time. It can also show other telemetry like requests, dependencies, and traces.

Note

Live metrics are enabled by default when you onboard it by using the recommended instructions for .NET applications.

Enable live metrics by using code for any .NET application

To manually configure live metrics:

  1. Install the NuGet package Microsoft.ApplicationInsights.PerfCounterCollector.

  2. The following sample console app code shows setting up live metrics:

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

To manually configure live metrics:

  1. Install the NuGet package Microsoft.ApplicationInsights.PerfCounterCollector.

  2. The following sample console app code shows setting up live metrics:

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;

// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
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();
}

The preceding sample is for a console app, but the same code can be used in any .NET applications.

Important

If any other telemetry modules are enabled to autocollect telemetry, ensure that the same configuration used for initializing those modules is used for the live metrics module.

ILogger logs

The default configuration collects ILogger Warning logs and more severe logs. For more information, see How do I customize ILogger logs collection?.

Dependencies Automatically tracked dependencies

Application Insights SDKs for .NET and .NET Core ship with DependencyTrackingTelemetryModule, which is a telemetry module that automatically collects dependencies. The module DependencyTrackingTelemetryModule is shipped as the Microsoft.ApplicationInsights.DependencyCollector NuGet package and brought automatically when you use either the Microsoft.ApplicationInsights.Web NuGet package or the Microsoft.ApplicationInsights.AspNetCore NuGet package.

Currently, DependencyTrackingTelemetryModule tracks the following dependencies automatically:

If the dependency isn't autocollected, you can track it manually with a track dependency call.

For more information about how dependency tracking works, see Dependency tracking in Application Insights.

Set up automatic dependency tracking in console apps

To automatically track dependencies from .NET console apps, install the NuGet package Microsoft.ApplicationInsights.DependencyCollector and initialize DependencyTrackingTelemetryModule:

    DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();
    depModule.Initialize(TelemetryConfiguration.Active);

For .NET Core console apps, TelemetryConfiguration.Active is obsolete. See the guidance in the Worker service documentation and the ASP.NET Core tabs in this article.

Manually tracking dependencies

The following examples of dependencies, which aren't automatically collected, require manual tracking:

For those dependencies not automatically collected by SDK, you can track them manually by using the TrackDependency API that's used by the standard autocollection modules.

Example

If you build your code with an assembly that you didn't write yourself, you could time all the calls to it. This scenario would allow you to find out what contribution it makes to your response times.

To have this data displayed in the dependency charts in Application Insights, send it by using TrackDependency:


    var startTime = DateTime.UtcNow;
    var timer = System.Diagnostics.Stopwatch.StartNew();
    try
    {
        // making dependency call
        success = dependency.Call();
    }
    finally
    {
        timer.Stop();
        telemetryClient.TrackDependency("myDependencyType", "myDependencyCall", "myDependencyData",  startTime, timer.Elapsed, success);
    }

Alternatively, TelemetryClient provides the extension methods StartOperation and StopOperation, which can be used to manually track dependencies as shown in Outgoing dependencies tracking.

Disabling the standard dependency tracking module Advanced SQL tracking to get full SQL query

For SQL calls, the name of the server and database is always collected and stored as the name of the collected DependencyTelemetry. Another field, called data, can contain the full SQL query text.

For ASP.NET applications, the full SQL query text is collected with the help of byte code instrumentation, which requires using the instrumentation engine or by using the Microsoft.Data.SqlClient NuGet package instead of the System.Data.SqlClient library. Platform-specific steps to enable full SQL Query collection are described in the following table.

In addition to the preceding platform-specific steps, you must also explicitly opt in to enable SQL command collection by modifying the applicationInsights.config file with the following code:

<TelemetryModules>
  <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
    <EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
  </Add>

For ASP.NET Core applications, It's now required to opt in to SQL Text collection by using:

services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module. EnableSqlCommandTextInstrumentation = true; });

In the preceding cases, the proper way of validating that the instrumentation engine is correctly installed is by validating that the SDK version of collected DependencyTelemetry is rddp. Use of rdddsd or rddf indicates dependencies are collected via DiagnosticSource or EventSource callbacks, so the full SQL query won't be captured.

Performance counters

ASP.NET fully supports performance counters, while ASP.NET Core offers limited support depending on the SDK version and hosting environment. For more information, see Counters for .NET in Application Insights.

Event counters

Application Insights supports collecting EventCounters with its EventCounterCollectionModule, which is enabled by default for ASP.NET Core. To learn how to configure the list of counters to be collected, see Counters for .NET in Application Insights.

Enrich data through HTTP
var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;

if (requestTelemetry != null)
{
    requestTelemetry.Properties["myProp"] = "someData";
}
HttpContext.Features.Get<RequestTelemetry>().Properties["myProp"] = someData
Configure the Application Insights SDK

You can customize the Application Insights SDK for ASP.NET and ASP.NET Core to change the default configuration.

To learn how to configure the Application Insights SDK for ASP.NET applications, see Configure the Application Insights SDK with ApplicationInsights.config or .xml.

In ASP.NET Core applications, all configuration changes are made in the ConfigureServices() method of your Startup.cs class, unless otherwise directed.

Note

In ASP.NET Core applications, changing configuration by modifying TelemetryConfiguration.Active isn't supported.

Use ApplicationInsightsServiceOptions

You can modify a few common settings by passing ApplicationInsightsServiceOptions to AddApplicationInsightsTelemetry, as in this example:

var builder = WebApplication.CreateBuilder(args);

var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

// Disables adaptive sampling.
aiOptions.EnableAdaptiveSampling = false;

// Disables live metrics (also known as QuickPulse).
aiOptions.EnableQuickPulseMetricStream = false;

builder.Services.AddApplicationInsightsTelemetry(aiOptions);
var app = builder.Build();

This table has the full list of ApplicationInsightsServiceOptions settings:

Setting Description Default EnablePerformanceCounterCollectionModule Enable/Disable PerformanceCounterCollectionModule. True EnableRequestTrackingTelemetryModule Enable/Disable RequestTrackingTelemetryModule. True EnableEventCounterCollectionModule Enable/Disable EventCounterCollectionModule. True EnableDependencyTrackingTelemetryModule Enable/Disable DependencyTrackingTelemetryModule. True EnableAppServicesHeartbeatTelemetryModule Enable/Disable AppServicesHeartbeatTelemetryModule. True EnableAzureInstanceMetadataTelemetryModule Enable/Disable AzureInstanceMetadataTelemetryModule. True EnableQuickPulseMetricStream Enable/Disable LiveMetrics feature. True EnableAdaptiveSampling Enable/Disable Adaptive Sampling. True EnableHeartbeat Enable/Disable the heartbeats feature. It periodically (15-min default) sends a custom metric named HeartbeatState with information about the runtime like .NET version and Azure environment information, if applicable. True AddAutoCollectedMetricExtractor Enable/Disable the AutoCollectedMetrics extractor. This telemetry processor sends preaggregated metrics about requests/dependencies before sampling takes place. True RequestCollectionOptions.TrackExceptions Enable/Disable reporting of unhandled exception tracking by the request collection module. False in netstandard2.0 (because exceptions are tracked with ApplicationInsightsLoggerProvider). True otherwise. EnableDiagnosticsTelemetryModule Enable/Disable DiagnosticsTelemetryModule. Disabling causes the following settings to be ignored: EnableHeartbeat, EnableAzureInstanceMetadataTelemetryModule, and EnableAppServicesHeartbeatTelemetryModule. True

For the most current list, see the configurable settings in ApplicationInsightsServiceOptions.

Configuration recommendation for Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 and later

In Microsoft.ApplicationInsights.AspNetCore SDK version 2.15.0 and later, configure every setting available in ApplicationInsightsServiceOptions, including ConnectionString. Use the application's IConfiguration instance. The settings must be under the section ApplicationInsights, as shown in the following example. The following section from appsettings.json configures the connection string and disables adaptive sampling and performance counter collection.

{
    "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000",
    "EnableAdaptiveSampling": false,
    "EnablePerformanceCounterCollectionModule": false
    }
}

If builder.Services.AddApplicationInsightsTelemetry(aiOptions) for ASP.NET Core 6.0 or services.AddApplicationInsightsTelemetry(aiOptions) for ASP.NET Core 3.1 and earlier is used, it overrides the settings from Microsoft.Extensions.Configuration.IConfiguration.

Sampling Telemetry initializers

To enrich telemetry with additional information or to override telemetry properties set by the standard telemetry modules, use telemetry initializers.

To learn how to use telemetry initializers with ASP.NET applications, see Filter and preprocess telemetry in the Application Insights SDK.

Add telemetry initializers

Add any new TelemetryInitializer to the DependencyInjection container as shown in the following code. The SDK automatically picks up any TelemetryInitializer that's added to the DependencyInjection container.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();

var app = builder.Build();

Note

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>(); works for simple initializers. For others, builder.Services.AddSingleton(new MyCustomTelemetryInitializer() { fieldName = "myfieldName" }); is required.

Remove telemetry initializers

By default, telemetry initializers are present. To remove all or specific telemetry initializers, use the following sample code after calling AddApplicationInsightsTelemetry().

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// Remove a specific built-in telemetry initializer
var tiToRemove = builder.Services.FirstOrDefault<ServiceDescriptor>
                    (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));
if (tiToRemove != null)
{
    builder.Services.Remove(tiToRemove);
}

// Remove all initializers
// This requires importing namespace by using Microsoft.Extensions.DependencyInjection.Extensions;
builder.Services.RemoveAll(typeof(ITelemetryInitializer));

var app = builder.Build();
Telemetry processors

To learn how to use telemetry processors with ASP.NET applications, see Filter and preprocess telemetry in the Application Insights SDK.

Add telemetry processors

You can add custom telemetry processors to TelemetryConfiguration by using the extension method AddApplicationInsightsTelemetryProcessor on IServiceCollection. You use telemetry processors in advanced filtering scenarios. Use the following example:

var builder = WebApplication.CreateBuilder(args);

// ...
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();

// If you have more processors:
builder.Services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();

var app = builder.Build();
Configure or remove default TelemetryModules

Application Insights automatically collects telemetry about specific workloads without requiring manual tracking by user.

By default, the following automatic-collection modules are enabled. These modules are responsible for automatically collecting telemetry. You can disable or configure them to alter their default behavior.

To learn how to configure or remove telemetry modules for ASP.NET application, see Configure the Application Insights SDK with ApplicationInsights.config or .xml.

To configure any default TelemetryModule, use the extension method ConfigureTelemetryModule<T> on IServiceCollection, as shown in the following example:

using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// The following configures DependencyTrackingTelemetryModule.
// Similarly, any other default modules can be configured.
builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
        {
            module.EnableW3CHeadersInjection = true;
        });

// The following removes all default counters from EventCounterCollectionModule, and adds a single one.
builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>((module, o) =>
        {
            module.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
        });

// The following removes PerformanceCollectorModule to disable perf-counter collection.
// Similarly, any other default modules can be removed.
var performanceCounterService = builder.Services.FirstOrDefault<ServiceDescriptor>(t => t.ImplementationType == typeof(PerformanceCollectorModule));
if (performanceCounterService != null)
{
    builder.Services.Remove(performanceCounterService);
}

var app = builder.Build();

In versions 2.12.2 and later, ApplicationInsightsServiceOptions includes an easy option to disable any of the default modules.

Configure a telemetry channel

The default telemetry channel is ServerTelemetryChannel. The following example shows how to override it.

using Microsoft.ApplicationInsights.Channel;

var builder = WebApplication.CreateBuilder(args);

// Use the following to replace the default channel with InMemoryChannel.
// This can also be applied to ServerTelemetryChannel.
builder.Services.AddSingleton(typeof(ITelemetryChannel), new InMemoryChannel() {MaxTelemetryBufferCapacity = 19898 });

builder.Services.AddApplicationInsightsTelemetry();

var app = builder.Build();

Note

If you want to flush the buffer, see Flushing data. For example, you might need to flush the buffer if you're using the SDK in an application that shuts down.

Disable telemetry dynamically

If you want to disable telemetry conditionally and dynamically, you can resolve the TelemetryConfiguration instance with an ASP.NET Core dependency injection container anywhere in your code and set the DisableTelemetry flag on it.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// any custom configuration can be done here:
builder.Services.Configure<TelemetryConfiguration>(x => x.DisableTelemetry = true);

var app = builder.Build();

The preceding code sample prevents the sending of telemetry to Application Insights. It doesn't prevent any automatic collection modules from collecting telemetry. If you want to remove a particular autocollection module, see Remove the telemetry module.

Add client-side monitoring

The previous sections provided guidance on methods to automatically and manually configure server-side monitoring. To add client-side monitoring, use the client-side JavaScript SDK. You can monitor any web page's client-side transactions by adding a JavaScript (Web) SDK Loader Script before the closing </head> tag of the page's HTML.

Although it's possible to manually add the JavaScript (Web) SDK Loader Script to the header of each HTML page, we recommend that you instead add the JavaScript (Web) SDK Loader Script to a primary page. That action injects the JavaScript (Web) SDK Loader Script into all pages of a site.

For the template-based ASP.NET MVC app from this article, the file that you need to edit is _Layout.cshtml. You can find it under Views > Shared. To add client-side monitoring, open _Layout.cshtml and follow the JavaScript (Web) SDK Loader Script-based setup instructions from the article about client-side JavaScript SDK configuration.

If your application has client-side components, follow the next steps to start collecting usage telemetry using JavaScript (Web) SDK Loader Script injection by configuration.

  1. In _ViewImports.cshtml, add injection:

    @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    
  2. In _Layout.cshtml, insert HtmlHelper at the end of the <head> section but before any other script. If you want to report any custom JavaScript telemetry from the page, inject it after this snippet:

        @Html.Raw(JavaScriptSnippet.FullScript)
    </head>
    

As an alternative to using FullScript, ScriptBody is available starting in Application Insights SDK for ASP.NET Core version 2.14. Use ScriptBody if you need to control the <script> tag to set a Content Security Policy:

<script> // apply custom changes to this script tag.
    @Html.Raw(JavaScriptSnippet.ScriptBody)
</script>

The .cshtml file names referenced earlier are from a default MVC application template. Ultimately, if you want to properly enable client-side monitoring for your application, the JavaScript (Web) SDK Loader Script must appear in the <head> section of each page of your application that you want to monitor. Add the JavaScript (Web) SDK Loader Script to _Layout.cshtml in an application template to enable client-side monitoring.

If your project doesn't include _Layout.cshtml, you can still add client-side monitoring by adding the JavaScript (Web) SDK Loader Script to an equivalent file that controls the <head> of all pages within your app. Alternatively, you can add the JavaScript (Web) SDK Loader Script to multiple pages, but we don't recommend it.

Note

JavaScript injection provides a default configuration experience. If you require configuration beyond setting the connection string, you're required to remove autoinjection as described and manually add the JavaScript SDK.

Troubleshooting

See the dedicated troubleshooting article.

There's a known issue in Visual Studio 2019: storing the instrumentation key or connection string in a user secret is broken for .NET Framework-based apps. The key ultimately has to be hardcoded into the applicationinsights.config file to work around this bug. This article is designed to avoid this issue entirely, by not using user secrets.

Test connectivity between your application host and the ingestion service

Application Insights SDKs and agents send telemetry to get ingested as REST calls to our ingestion endpoints. You can test connectivity from your web server or application host machine to the ingestion service endpoints by using raw REST clients from PowerShell or curl commands. See Troubleshoot missing application telemetry in Azure Monitor Application Insights.

Open-source SDK

Read and contribute to the code.

For the latest updates and bug fixes, consult the release notes.

Release Notes

For version 2.12 and newer: .NET Software Development Kits (SDKs) including ASP.NET, ASP.NET Core, and Logging Adapters

Our Service Updates also summarize major Application Insights improvements.

Next steps

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4