ASP.NET Core ASP.NET Core Application Insights

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core Application Insights

ASP.NET Core Application Insights

Overview

Application Insights, a part of Azure Application Services, is a powerful analytics service offered by Microsoft to monitor and diagnose web applications in real-time. It supports several development frameworks, including ASP.NET Core, which is a modern, high-performance, open-source framework for building web applications.

Key Features

  1. Telemetry Collection

    • Requests: Tracks HTTP requests to understand the performance and availability of your application.
    • Dependencies: Captures calls to external services like databases, HTTP endpoints, and third-party APIs.
    • Exceptions: Logs unhandled exceptions to help diagnose issues.
    • Performance Counters: Provides insights into system metrics such as CPU usage, memory, and disk I/O.
    • Usage Data: Tracks user interactions and behavior.
  2. Real-Time Monitoring

    • Provides real-time analytics to keep developers informed about application health and performance metrics.
  3. Performance Analysis

    • Analyzes request processing times to identify performance bottlenecks.
    • Visualizes data through graphs and charts for easy interpretation.
  4. Smart Detectors

    • Detects anomalies in the application performance and sends alerts or recommendations to developers.
  5. User Experience Monitoring

    • Measures browser transactions to help optimize front-end performance.
  6. Workbooks

    • Helps in creating custom dashboards and reports based on the collected data.

Setting Up Application Insights for ASP.NET Core

To integrate Application Insights into an ASP.NET Core application, follow these steps:

  1. Create and Configure Application Insights Resource

    • Log in to the Azure portal and create a new Application Insights resource.
    • Copy the instrumentation key from the overview section of the resource.
  2. Install Application Insights SDK

    • Use NuGet to install the SDK by running the following command in the Package Manager Console:
      Install-Package Microsoft.ApplicationInsights.AspNetCore
      
  3. Register Application Insights Service

    • In the Startup.cs file, register the Application Insights services with the dependency injection container:
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddApplicationInsightsTelemetry();
      }
      
  4. Configure Telemetry

    • Configure telemetry collection in the appsettings.json file:
      "ApplicationInsights": {
          "InstrumentationKey": "<YourInstrumentationKey>"
      }
      
  5. Run the Application

    • Once the setup is complete, run the application. Application Insights will start collecting telemetry data from your application.

Best Practices

  • Enable Tracking Early: Integrate Application Insights at the initial stages of development to benefit from continuous monitoring.
  • Custom Telemetry: Use custom telemetry points for specific scenarios such as feature usage, business events, etc.
  • Security Accommodations: Ensure that personal data is handled according to compliance requirements when using Application Insights.
  • Review Documentation: Stay updated with the official Microsoft documentation for the latest features and best practices.

Conclusion

Application Insights offers comprehensive monitoring and analytics for ASP.NET Core applications, providing deep insights into application performance, usage, and health. Its real-time capabilities enable developers to proactively manage issues, optimize performance, and deliver better user experiences.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core Application Insights

Step 1: Create a New ASP.NET Core Project

If you don't have an existing project, you can start by creating a new ASP.NET Core project.

Using Visual Studio:

  1. Open Visual Studio.
  2. Select Create a new project.
  3. Choose ASP.NET Core Web App (Model-View-Controller) or ASP.NET Core Web App (Razor Pages) template based on your preference.
  4. Click Next.
  5. Enter your project name and location.
  6. Click Create.
  7. Choose the target framework (e.g., .NET 7.0) and click Create.

Using .NET CLI:

Navigate to the directory where you want to create the project and run:

dotnet new mvc -n MyAspNetApp
cd MyAspNetApp

Step 2: Install Application Insights NuGet Packages

To use Application Insights in your ASP.NET Core app, you need to install the Microsoft.ApplicationInsights.AspNetCore package.

Using Visual Studio:

  1. In Visual Studio, right-click on your project in the Solution Explorer and select Manage NuGet Packages.
  2. In the NuGet Package Manager, go to the Browse tab.
  3. Search for Microsoft.ApplicationInsights.AspNetCore.
  4. Select the package and click Install.

Using .NET CLI:

Run the following command in your project directory:

dotnet add package Microsoft.ApplicationInsights.AspNetCore

Step 3: Configure Application Insights

There are two main ways to configure Application Insights in an ASP.NET Core project:

a. Using the Azure Portal

  1. Create an Application Insights Resource:

    • Go to the Azure Portal.
    • Click on Create a resource.
    • Search for Application Insights and select it.
    • Click Create.
    • Fill in the required details (e.g., Name, Resource Group, Subscription, Region) and click Review + create.
    • Click Create after reviewing the settings.
  2. Get the Instrumentation Key:

    • Once the resource is deployed, go to your Application Insights resource in the Azure Portal.
    • Click on Overview.
    • Copy the Instrumentation Key.
  3. Add the Instrumentation Key to your App:

    • Open the appsettings.json file in your project.
    • Add an ApplicationInsights section with the instrumentation key:
      {
        "ApplicationInsights": {
          "InstrumentationKey": "<Your-Application-Insights-Instrumentation-Key>"
        }
      }
      
  4. Enable Application Insights in Program.cs:

    • Open the Program.cs file in your project.
    • Ensure that AddApplicationInsightsTelemetry is called to register Application Insights services:
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      builder.Services.AddControllersWithViews();
      builder.Services.AddApplicationInsightsTelemetry();
      
      var app = builder.Build();
      
      // Configure the HTTP request pipeline.
      if (!app.Environment.IsDevelopment())
      {
          app.UseExceptionHandler("/Home/Error");
          app.UseHsts();
      }
      
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      
      app.UseRouting();
      
      app.UseAuthorization();
      
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      
      app.Run();
      

b. Using Connected Services (Visual Studio Only)

  1. Open Connected Services:

    • Right-click on your ASP.NET Core project in the Solution Explorer.
    • Select Add > Connected Services.
  2. Add Application Insights:

    • In the list of connected services, select Application Insights and click Next.
    • If you have existing Azure subscriptions, you can select the Application Insights resource from the list. Otherwise, create a new one.
    • Click Finish to configure Application Insights in your project.

Step 4: Verify Application Insights Configuration

To verify that Application Insights is correctly configured, you can add some telemetry data to your application.

Example: Track a Page View

  1. Modify a Controller or Razor Page:

    • Open the HomeController.cs file (or another controller of your choice).
    • Add ApplicationInsights telemetry:
      using Microsoft.AspNetCore.Mvc;
      using Microsoft.ApplicationInsights;
      using Microsoft.ApplicationInsights.DataContracts;
      
      public class HomeController : Controller
      {
          private readonly TelemetryClient _telemetryClient;
      
          public HomeController(TelemetryClient telemetryClient)
          {
              _telemetryClient = telemetryClient;
          }
      
          public IActionResult Index()
          {
              _telemetryClient.TrackPageView(new PageViewTelemetry("HomePage"));
              return View();
          }
      
          // Other actions...
      }
      
  2. Run the Application:

    • Start your ASP.NET Core application.
    • Navigate to the page you modified (e.g., the Home page).
    • Go back to the Azure Portal and navigate to your Application Insights resource.
    • In the Overview blade, you should see data flowing in, and you can explore various metrics, logs, and insights.

Step 5: Explore Telemetry Data

Application Insights provides a wide range of data that you can explore to monitor and troubleshoot your application.

  • Overview: Provides a summary of critical metrics.
  • Performance: Shows details about page load times, server processing times, and dependencies.
  • Failed Requests: Lists requests that failed.
  • Server Logs: Displays detailed logs.
  • Crashes: Shows any crashes that occurred in your application.
  • Live Metrics: Provides real-time telemetry data.

Step 6: (Optional) Configure Custom Telemetry

You can add custom telemetry to provide more insights into your application's behavior.

Example: Track a Custom Event

  1. Modify a Controller or Razor Page:

    • Add a custom event:
      public IActionResult SomeAction()
      {
          var properties = new Dictionary<string, string>
          {
              { "CustomKey1", "CustomValue1" },
              { "CustomKey2", "CustomValue2" }
          };
      
          _telemetryClient.TrackEvent("CustomEvent", properties);
      
          return View();
      }
      
  2. Check in Azure Portal:

    • Navigate to your Application Insights resource.
    • Click on Custom Events.
    • You should see your custom event listed there.

Summary

Top 10 Interview Questions & Answers on ASP.NET Core Application Insights

Top 10 Questions and Answers on ASP.NET Core Application Insights

1. What is Application Insights and why should I use it in my ASP.NET Core application?

  • Monitor performance telemetry: Capture metrics about application performance, such as request latency.
  • Exception tracking: Gather detailed exception information to understand crashes.
  • Usage metrics: Understand how users interact with your application.
  • Dependency tracking: Monitor calls to third-party services, databases, and APIs.
  • Real-time analytics: Get immediate feedback on user experience and application health.
  • Log data: Diagnose and fix issues from logs and trace data generated by your application.

2. How do I integrate Application Insights into an ASP.NET Core project?

To integrate Application Insights into an ASP.NET Core project, follow these steps:

  1. Install the NuGet package: Use the Package Manager Console or .NET CLI to add the Microsoft.ApplicationInsights.AspNetCore package to your project:

    dotnet add package Microsoft.ApplicationInsights.AspNetCore --version <latest_version>
    
  2. Configure Application Insights: Modify your app's appsettings.json file to include your instrumentation key:

    {
      "ApplicationInsights": {
        "InstrumentationKey": "<your-instrumentation-key>"
      }
    }
    
  3. Add Application Insights to the service container: In your Program.cs or Startup.cs, add Application Insights services in the method where services are configured:

    using Microsoft.ApplicationInsights.Extensibility;
    
    // For .NET 6 minimal APIs
    builder.Services.AddApplicationInsightsTelemetry();
    
    // For older projects, use Startup.cs ConfigureServices()
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
    }
    
  4. Instrument your code: Although most common data is collected automatically, you can manually track additional events, requests, and other telemetry as needed. For instance:

    using Microsoft.ApplicationInsights;
    public class SampleController : Controller
    {
        private TelemetryClient _client;
    
        public SampleController(TelemetryClient client)
        {
            _client = client;
        }
    
        public IActionResult Index()
        {
            _client.TrackPageView("IndexView");
            return View();
        }
    }
    

3. Can I use Application Insights without a NuGet package?

No, Application Insights requires a NuGet package (Microsoft.ApplicationInsights.AspNetCore) to access its SDK functions and collect telemetry data efficiently. However, starting from .NET 6, there’s an out-of-the-box integration option through Visual Studio’s wizard which automatically sets up the necessary configuration.

4. How do I configure logging with Application Insights in ASP.NET Core?

You can enhance logging capabilities by adding Application Insights to the logging pipeline in your ASP.NET Core project:

  1. Install required NuGet packages:

    dotnet add package Microsoft.Extensions.Logging.ApplicationInsights
    
  2. Configure logging in Program.cs:

    builder.Host.ConfigureLogging(logging =>
    {
        logging.AddApplicationInsights("<your-instrumentation-key>");
    });
    

    For older projects:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddApplicationInsights("<your-instrumentation-key>");
    }
    
  3. Use the logger in your controllers or other components:

    public class MyController : ControllerBase
    {
        private readonly ILogger<MyController> _logger;
    
        public MyController(ILogger<MyController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet]
        public IActionResult Get()
        {
            try 
            {
                // Perform operations...
            } 
            catch (Exception ex) 
            {
                _logger.LogError(ex, "Error occurred while processing request.");
            }
    
            return Ok();
        }
    }
    

5. How do I customize the telemetry collected by Application Insights in ASP.NET Core?

Customize the telemetry collection by creating a TelemetryProcessor or TelemetryInitializer:

  1. Create a new TelemetryInitializer:

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.Extensibility;
    
    public class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
            {
                telemetry.Context.Cloud.RoleName = "My Web Application";
            }
    
            var requestTelemetry = telemetry as RequestTelemetry;
            if (requestTelemetry != null)
            {
                requestTelemetry.Properties["AppSetting"] = "Custom value";
            }
        }
    }
    
  2. Register the TelemetryInitializer in ConfigureServices():

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
        services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
    }
    
  3. Create a new TelemetryProcessor:

    using Microsoft.ApplicationInsights.DataContracts;
    using Microsoft.ApplicationInsights.Extensibility;
    
    public class MyTelemetryFilter : ITelemetryProcessor
    {
        private ITelemetryProcessor _next;
    
        public MyTelemetryFilter(ITelemetryProcessor next)
        {
            _next = next;
        }
    
        public void Process(ITelemetry item)
        {
            if (!this.OkToSend(item)) { return; }
            _next.Process(item);
        }
    
        private bool OkToSend(ITelemetry item)
        {
            var metric = item as MetricTelemetry;
            if (metric?.Name == "IgnoreThisMetric") { return false; }
    
            var request = item as RequestTelemetry;
            if (request?.Name == "IgnoreThisRequest") { return false; }
    
            return true;
        }
    }
    
  4. Register the TelemetryProcessor in ConfigureServices():

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
    
        services.AddApplicationInsightsTelemetryProcessor<MyTelemetryFilter>();
    }
    

6. How can I exclude specific URLs or routes from Application Insights monitoring?

You can exclude URLs using an ITelemetryProcessor. Here's an example:

public class IgnorePathsTelemetryFilter : ITelemetryProcessor
{
    private ITelemetryProcessor _next;
    private List<string> _ignoreRoutes;

    public IgnorePathsTelemetryFilter(ITelemetryProcessor next, IConfiguration config)
    {
        _next = next;
        _ignoreRoutes = config.GetSection("ApplicationInsights:IgnoreRoutes").Get<List<string>>();
    }

    public void Process(ITelemetry item)
    {
        var requestTelemetry = item as RequestTelemetry;
        if(requestTelemetry != null)
        {
            // Check if this URL needs to be ignored
            if (_ignoreRoutes.Any(route => requestTelemetry.Context.Operation.Name.Equals($"GET {_baseUrl}{route}", StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }
        }

        _next.Process(item);
    }
}

In appsettings.json, add the paths you want to ignore:

{
    "ApplicationInsights": {
        "IgnoreRoutes": [
          "api/healthcheck",
          "metrics"
        ]
    }
}

Register processor:

services.AddApplicationInsightsTelemetryProcessor<IgnorePathsTelemetryFilter>();

7. How do I enable Live Metrics Stream with Application Insights in ASP.NET Core?

Live Metrics Stream displays real-time performance metrics for your application in Azure portal:

  • Navigate to your Application Insights resource in the Azure portal.
  • Open the Live Metrics Stream blade.
  • Ensure that SDK version is above 2.9.0-beta1 as live metrics feature relies on the newer SDK versions.
  • The live dashboard appears immediately after receiving data.

In newer versions of Microsoft.ApplicationInsights.AspNetCore (2.18+), it’s enabled by default and requires no extra configuration. Just ensure that your application is sending telemetry correctly.

8. Is it possible to view local telemetry when developing an ASP.NET Core app locally?

Yes, you can view local telemetry during development by configuring Application Insights to send data either to a console or an Azure account:

  • Console Telemetry Channel:

    services.AddApplicationInsightsTelemetry(options =>
    {
       options.TelemetryChannelType = typeof(Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel);
    });
    
    services.Configure<TelemetryConfiguration>(config =>
    {
        config.TelemetryChannel.DeveloperMode = true;
    });
    
  • Local Development Endpoint:

    Microsoft also provides a local debug proxy but setup can be more complex for non-production scenarios.

Best to leverage Developer Mode temporarily due to overhead involved in pushing telemetry directly.

9. How does Application Insights monitor external dependencies in an ASP.NET Core app like databases, HTTP clients, etc.?

Application Insights uses automatic instrumentation to monitor various dependencies including HTTP clients, SQL databases, and other services when you install the Microsoft.ApplicationInsights.AspNetCore package. It captures details on duration, success or failure, and other relevant info without requiring any modification to your existing service calls.

However, for cases where automatic detection fails or when utilizing specialized libraries not supported by default, consider using TrackDependency() explicitly:

using Microsoft.ApplicationInsights;
public class MyService
{
    private readonly TelemetryClient _telemetryClient;

    public MyService(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    public async Task<bool> CheckResourceAsync(string name)
    {
        var startTime = DateTimeOffset.UtcNow;

        try
        {
            await SomeHttpClient.GetAsync(name).ConfigureAwait(false);
            return true;
        }
        catch(Exception e)
        {
            _telemetryClient.TrackException(e);
            return false;
        }
        finally
        {
            var duration = DateTimeOffset.UtcNow - startTime;
            var dependencyTelemetry = new DependencyTelemetry
            {
                Name = name,
                Target = "api.example.com",
                Data = $"GET /{name}",
                Timestamp = startTime,
                Duration = duration,
                Success = true // Adjust as necessary based on the result.
            };
            
            _telemetryClient.TrackDependency(dependencyTelemetry);
        }

    }
}

10. How can I correlate transactions across multiple services using Application Insights in ASP.NET Core?

Correlating transactions across multiple services in Application Insights involves proper handling of trace context headers (Request-Id):

  • Automatic Propagation: When using HttpClient, ASP.NET Core SDK automatically propogates correlation IDs for outbound HTTP requests making it possible to correlate traces.

  • Manual Propagation (For other services):

    If you are manually invoking a service (like Azure Service Bus, Redis, etc.) or making custom API calls, you need to manually pass the Request-Id.

Here’s an example using a background task:

public class MyJobBackgroundService : BackgroundService
{
    private readonly TelemetryClient _telemetryClient;

    public MyJobBackgroundService(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var operation = _telemetryClient.StartOperation<RequestTelemetry>("My Background Job"))
        {
            try
            {
                // Simulate a service request
                await SimulateExternalServiceCallAsync(operation.RootId, operation.ParentId);

                operation.Telemetry.Success = true;
            }
            catch(Exception ex)
            {
                _telemetryClient.TrackException(ex);
                operation.Telemetry.Success = false;
                throw;
            }
            finally
            {
                _telemetryClient.StopOperation(operation);
            }

        }
    }

    private async Task SimulateExternalServiceCallAsync(string rootId, string parentId)
    {
        // Create a new telemetry client specifically for this call.
        var callTelemetryClient = new TelemetryClient(_telemetryClient.ActiveConfiguration);
        
        // Manually set the ids of the parent operation.
        var callTelemetry = new DependencyTelemetry
        {
            Name = "SimulateExternalServiceCall",
            Type = "MyDependencyType", // Custom name as per your domain.
            Id = $"{rootId}.{parentId}.1", // This is a unique id for this dependency call within the parent operation.
            Target = "example-dependency.com",
            Success = true
        };

        // Start & stop dependency timing.
        using(_telemetryClient.StartOperation(callTelemetry))
        {
            // Simulate service work.    
        }
    }
}

In this example, we’re manually setting the RootId, ParentId, and constructing an Id for each dependency operation ensuring they get correlated correctly in the Application Insights dashboard.

You May Like This Related .NET Topic

Login to post a comment.