Real-time Monitoring with Azure Application Insights in ASP.NET Core Web API

Introduction

Azure Application Insights is a powerful tool for monitoring and diagnosing applications, including ASP.NET Core Web APIs. It provides real-time telemetry data, performance metrics, and logging capabilities. In this example, I'll walk you through setting up Azure Application Insights for an ASP.NET Core Web API and demonstrate how to use it for real-time monitoring and diagnostics.

Prerequisites

  1. An Azure account with Application Insights enabled.
  2. Visual Studio or Visual Studio Code.
  3. ASP.NET Core Web API project.

Step 1. Create an ASP.NET Core Web API

If you haven't already, create an ASP.NET Core Web API project. You can do this using the following command.

dotnet new AzureAppInsights -n AzureAppInsightsProject

Step 2. Add Application Insights to your project

  1. Open your project in Visual Studio or Visual Studio Code.
  2. Install the Microsoft.ApplicationInsights.AspNetCore package using NuGet.
dotnet add package Microsoft.ApplicationInsights.AspNetCore

In your Startup.cs file, add the following code to configure Application Insights.

Note. Please use the Asp.net Core 5 for setting up a project in your local Environment.

using Microsoft.ApplicationInsights.Extensibility;

Author: Sardar Mudassar Ali Khan
public class Startup
{
   
    public void ConfigureServices(IServiceCollection services)
    {
        
        services.AddApplicationInsightsTelemetry(Configuration["ApplicationInsights:InstrumentationKey"]);
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      
        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
   
    }
}

In your appsettings.json file, add your Application Insights instrumentation key.

Author: Sardar Mudassar Ali Khan
{
    "ApplicationInsights": {
        "InstrumentationKey": "YOUR_INSTRUMENTATION_KEY" //Replace this Key with your Azure Key 
    }
}

Step 3. Logging and Telemetry

You can now start using Application Insights for logging and telemetry in your Web API. Here's an example of how to log events and exceptions.

using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private readonly ILogger<ValuesController> _logger;
    private readonly TelemetryClient _telemetryClient;

    public ValuesController(ILogger<ValuesController> logger, TelemetryClient telemetryClient)
    {
        _logger = logger;
        _telemetryClient = telemetryClient;
    }

    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        try
        {
            // Simulate an exception for testing
            if (id == 0)
            {
                throw new Exception("Invalid ID");
            }

            // Log information
            _logger.LogInformation("Value requested: {Id}", id);

            // Track a custom event
            _telemetryClient.TrackEvent("ValueRequested", new { Id = id });

            return $"Value {id}";
        }
        catch (Exception ex)
        {
            // Log the exception
            _logger.LogError(ex, "An error occurred while processing the request.");

            // Track the exception
            _telemetryClient.TrackException(ex);

            return StatusCode(500, "An error occurred.");
        }
    }
}

Step 4. View Telemetry Data

You can now view telemetry data in the Azure portal by going to your Application Insights resource. You'll find real-time metrics, traces, and exceptions in the portal.

That's it! You've successfully set up Azure Application Insights for real-time monitoring, diagnostics, and logging in your ASP.NET Core Web API.

Conclusion

Azure Application Insights is a valuable tool for monitoring, diagnosing, and logging your ASP.NET Core Web API applications. By following the steps outlined in the example, you can effectively integrate Application Insights into your project and leverage its real-time monitoring and diagnostics capabilities. Here's a quick recap of the key points:

  1. Prerequisites: Ensure you have an Azure account with Application Insights enabled and a working ASP.NET Core Web API project.
  2. Add Application Insights: Install the Microsoft.ApplicationInsights.AspNetCore package and configure it in your Startup. cs file. Don't forget to add your Application Insights instrumentation key in the appsettings.json file.
  3. Logging and Telemetry: Use the ILogger and TelemetryClient to log events and exceptions in your Web API. You can customize what you log and track based on your application's requirements.
  4. View Telemetry and data, Access real-time telemetry data and performance metrics, and log in to the Azure portal by navigating to your Application Insights resource.

By following these steps and integrating Azure Application Insights into your ASP.NET Core Web API, you can gain valuable insights into your application's performance, troubleshoot issues in real time, and improve the overall reliability of your software.


Similar Articles