Muokkaa

Jaa


Application Insights for ASP.NET Core applications

This article describes how to enable and configure Application Insights for an ASP.NET Core application.

Caution

We recommend the Azure Monitor OpenTelemetry Distro for new applications or customers to power Azure Monitor Application Insights. The Azure Monitor OpenTelemetry Distro delivers a similar functionality and experience as the Application Insights SDK. It's possible to migrate from the Application Insights SDK using the migration guides for .NET, Node.js, and Python, but we are still working to add a few more features for backwards compatibility.

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

  • Requests
  • Dependencies
  • Exceptions
  • Performance counters
  • Heartbeats
  • Logs

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

An OpenTelemetry-based .NET offering is available. For more information, see OpenTelemetry overview.

Note

On March 31, 2025, support for instrumentation key ingestion will end. Instrumentation key ingestion will continue to work, but we'll no longer provide updates or support for the feature. Transition to connection strings to take advantage of new capabilities.

Note

If you want to use standalone ILogger provider, use Microsoft.Extensions.Logging.ApplicationInsight.

Supported scenarios

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 and covers the following scenarios:

  • Operating system: Windows, Linux, or Mac
  • Hosting method: In process or out of process
  • Deployment method: Framework dependent or self-contained
  • Web server: Internet Information Server (IIS) or Kestrel
  • Hosting platform: The Web Apps feature of Azure App Service, Azure Virtual Machines, Docker, and Azure Kubernetes Service (AKS)
  • .NET version: All officially supported .NET versions that aren't in preview
  • IDE: Visual Studio, Visual Studio Code, or command line

Prerequisites

  • A functioning ASP.NET Core application. If you need to create an ASP.NET Core application, follow this ASP.NET Core tutorial.
  • A reference to a supported version of the Application Insights NuGet package.
  • A valid Application Insights connection string. This string is required to send any telemetry to Application Insights. If you need to create a new Application Insights resource to get a connection string, see Create an Application Insights resource.

Enable Application Insights server-side telemetry (Visual Studio)

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

  1. Open your project in Visual Studio.

  2. Go to Project > Add Application Insights Telemetry.

  3. Select Azure Application Insights > Next.

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

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

  6. 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.

    Screenshot that shows where to select the Application Insights package for update.

Enable Application Insights server-side telemetry (no Visual Studio)

  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:

    • (Recommended) Set the connection string in configuration.

      Set the connection string in appsettings.json and make sure the configuration file is copied to the application root folder during publishing.

      {
          "Logging": {
              "LogLevel": {
                  "Default": "Information",
                  "Microsoft.AspNetCore": "Warning"
              }
          },
          "AllowedHosts": "*",
          "ApplicationInsights": {
              "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
          }
      }
      
    • Set the connection string in the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable or ApplicationInsights:ConnectionString in the JSON configuration file.

      For example:

      • SET ApplicationInsights:ConnectionString = <Copy connection string from Application Insights Resource Overview>
      • SET APPLICATIONINSIGHTS_CONNECTION_STRING = <Copy connection string from Application Insights Resource Overview>
      • Typically, APPLICATIONINSIGHTS_CONNECTION_STRING is used in Web Apps. It can also be used in all places where this SDK is supported.

      Note

      A connection string specified in code wins over the environment variable APPLICATIONINSIGHTS_CONNECTION_STRING, which wins over other options.

    • Set the connection string in code.

      Provide a connection string as part of the ApplicationInsightsServiceOptions argument to AddApplicationInsightsTelemetry in your program.cs class.

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.

Enable live metrics by using code for any .NET application

Note

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

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. If any other telemetry modules are enabled to autocollect telemetry, it's important to 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

Dependency collection is enabled by default. Dependency tracking in Application Insights explains the dependencies that are automatically collected and also contains steps to do manual tracking.

Performance counters

Support for performance counters in ASP.NET Core is limited:

  • SDK versions 2.4.1 and later collect performance counters if the application is running in Web Apps (Windows).
  • SDK versions 2.7.1 and later collect performance counters if the application is running in Windows and targets netstandard2.0 or later.
  • For applications that target the .NET Framework, all versions of the SDK support performance counters.
  • SDK versions 2.8.0 and later support the CPU/memory counter in Linux. No other counter is supported in Linux. To get system counters in Linux and other non-Windows environments, use EventCounters.

EventCounter

By default, EventCounterCollectionModule is enabled. To learn how to configure the list of counters to be collected, see EventCounters introduction.

Enrich data through HTTP

HttpContext.Features.Get<RequestTelemetry>().Properties["myProp"] = someData

Enable client-side telemetry for web applications

The preceding steps are enough to help you start collecting server-side telemetry. 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 auto-injection as described and manually add the JavaScript SDK.

Configure the Application Insights SDK

You can customize the Application Insights SDK for ASP.NET Core to change the default configuration. Users of the Application Insights ASP.NET SDK might be familiar with changing configuration by using ApplicationInsights.config or by modifying TelemetryConfiguration.Active. For ASP.NET Core, make almost all configuration changes in the ConfigureServices() method of your Startup.cs class, unless you're directed otherwise. The following sections offer more information.

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

The Application Insights SDK for ASP.NET Core supports both fixed-rate and adaptive sampling. By default, adaptive sampling is enabled.

For more information, see Configure adaptive sampling for ASP.NET Core applications.

Add TelemetryInitializers

When you want to enrich telemetry with more information, use 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 TelemetryInitializers

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

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.

  • RequestTrackingTelemetryModule: Collects RequestTelemetry from incoming web requests.
  • DependencyTrackingTelemetryModule: Collects DependencyTelemetry from outgoing HTTP calls and SQL calls.
  • PerformanceCollectorModule: Collects Windows PerformanceCounters.
  • QuickPulseTelemetryModule: Collects telemetry to show in the live metrics pane.
  • AppServicesHeartbeatTelemetryModule: Collects heartbeats (which are sent as custom metrics), about the App Service environment where the application is hosted.
  • AzureInstanceMetadataTelemetryModule: Collects heartbeats (which are sent as custom metrics), about the Azure VM environment where the application is hosted.
  • EventCounterCollectionModule: Collects EventCounters. This module is a new feature and is available in SDK version 2.8.0 and later.

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.

Frequently asked questions

This section provides answers to common questions.

Does Application Insights support ASP.NET Core 3.1?

ASP.NET Core 3.1 is no longer supported by Microsoft.

Application Insights SDK for ASP.NET Core version 2.8.0 and Visual Studio 2019 or later can be used with ASP.NET Core 3.1 applications.

How can I track telemetry that's not automatically collected?

Get an instance of TelemetryClient by using constructor injection and call the required TrackXXX() method on it. We don't recommend creating new TelemetryClient or TelemetryConfiguration instances in an ASP.NET Core application. A singleton instance of TelemetryClient is already registered in the DependencyInjection container, which shares TelemetryConfiguration with the rest of the telemetry. Create a new TelemetryClient instance only if it needs a configuration that's separate from the rest of the telemetry.

The following example shows how to track more telemetry from a controller.

using Microsoft.ApplicationInsights;

public class HomeController : Controller
{
    private TelemetryClient telemetry;

    // Use constructor injection to get a TelemetryClient instance.
    public HomeController(TelemetryClient telemetry)
    {
        this.telemetry = telemetry;
    }

    public IActionResult Index()
    {
        // Call the required TrackXXX method.
        this.telemetry.TrackEvent("HomePageRequested");
        return View();
    }
}

For more information about custom data reporting in Application Insights, see Application Insights custom metrics API reference. A similar approach can be used for sending custom metrics to Application Insights by using the GetMetric API.

How do I capture Request and Response body in my telemetry?

ASP.NET Core has built-in support for logging HTTP Request/Response information (including body) via ILogger. It's recommended to leverage this. This may potentially expose personally identifiable information (PII) in telemetry, and can cause costs (performance costs and Application Insights billing) to significantly increase, so evaluate the risks carefully before using this.

How do I customize ILogger logs collection?

The default setting for Application Insights is to only capture Warning and more severe logs.

Capture Information and less severe logs by changing the logging configuration for the Application Insights provider as follows.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        },
        "ApplicationInsights": {
            "LogLevel": {
                "Default": "Information"
            }
        }
    },
    "ApplicationInsights": {
        "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
    }
}

It's important to note that the following example doesn't cause the Application Insights provider to capture Information logs. It doesn't capture it because the SDK adds a default logging filter that instructs ApplicationInsights to capture only Warning logs and more severe logs. Application Insights requires an explicit override.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        }
    }
}

For more information, see ILogger configuration.

Some Visual Studio templates used the UseApplicationInsights() extension method on IWebHostBuilder to enable Application Insights. Is this usage still valid?

The extension method UseApplicationInsights() is still supported, but it's marked as obsolete in Application Insights SDK version 2.8.0 and later. It's removed in the next major version of the SDK. To enable Application Insights telemetry, use AddApplicationInsightsTelemetry() because it provides overloads to control some configuration. Also, in ASP.NET Core 3.X apps, services.AddApplicationInsightsTelemetry() is the only way to enable Application Insights.

I'm deploying my ASP.NET Core application to Web Apps. Should I still enable the Application Insights extension from Web Apps?

If the SDK is installed at build time as shown in this article, you don't need to enable the Application Insights extension from the App Service portal. If the extension is installed, it backs off when it detects the SDK is already added. If you enable Application Insights from the extension, you don't have to install and update the SDK. But if you enable Application Insights by following instructions in this article, you have more flexibility because:

  • Application Insights telemetry continues to work in:
    • All operating systems, including Windows, Linux, and Mac.
    • All publish modes, including self-contained or framework dependent.
    • All target frameworks, including the full .NET Framework.
    • All hosting options, including Web Apps, VMs, Linux, containers, AKS, and non-Azure hosting.
    • All .NET Core versions, including preview versions.
  • You can see telemetry locally when you're debugging from Visual Studio.
  • You can track more custom telemetry by using the TrackXXX() API.
  • You have full control over the configuration.

Can I enable Application Insights monitoring by using tools like Azure Monitor Application Insights Agent (formerly Status Monitor v2)?

Yes. In Application Insights Agent 2.0.0-beta1 and later, ASP.NET Core applications hosted in IIS are supported.

Are all features supported if I run my application in Linux?

Yes. Feature support for the SDK is the same in all platforms, with the following exceptions:

Is this SDK supported for Worker Services?

No. Instead, use Application Insights for Worker Service applications (non-HTTP applications) for worker services.

How can I uninstall the SDK?

To remove Application Insights, you need to remove the NuGet packages and references from the API in your application. You can uninstall NuGet packages by using the NuGet Package Manager in Visual Studio.

Note

These instructions are for uninstalling the ASP.NET Core SDK. If you need to uninstall the ASP.NET SDK, see How can I uninstall the ASP.NET SDK?.

  1. Uninstall the Microsoft.ApplicationInsights.AspNetCore package by using the NuGet Package Manager.
  2. To fully remove Application Insights, check and manually delete the added code or files along with any API calls you added in your project. For more information, see What is created when you add the Application Insights SDK?.

What is created when you add the Application Insights SDK?

When you add Application Insights to your project, it creates files and adds code to some of your files. Solely uninstalling the NuGet Packages won't always discard the files and code. To fully remove Application Insights, you should check and manually delete the added code or files along with any API calls you added in your project.

When you add Application Insights Telemetry to a Visual Studio ASP.NET Core template project, it adds the following code:

  • [Your project's name].csproj

    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <ApplicationInsightsResourceId>/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/Default-ApplicationInsights-EastUS/providers/microsoft.insights/components/WebApplication4core</ApplicationInsightsResourceId>
    </PropertyGroup>
    
    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.12.0" />
    </ItemGroup>
    
    <ItemGroup>
        <WCFMetadata Include="Connected Services" />
    </ItemGroup>
    
  • Appsettings.json

    "ApplicationInsights": {
        "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
    }
    
  • ConnectedService.json

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

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddApplicationInsightsTelemetry(); // This is added
        }
    

How can I disable telemetry correlation?

To disable telemetry correlation in code, see <ExcludeComponentCorrelationHttpHeadersOnDomains> in Application Insights for console applications.

Troubleshooting

See the dedicated troubleshooting article.

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, see the release notes.

Release Notes

For version 2.12 and newer: .NET SDKs (Including ASP.NET, ASP.NET Core, and Logging Adapters)

Our Service Updates also summarize major Application Insights improvements.

Next steps