Skip to main content

Command Palette

Search for a command to run...

Azure Application Insights

Monitoring Your .NET Applications with Azure Application Insights

Published
•4 min read•View as Markdown
Azure Application Insights
M

Morteza Jangjoo, Senior .NET Backend Developer with 15+ years of experience in C#, ASP.NET Core, SQL Server, and Microservices. Skilled in building scalable, high-performance systems.

When you deploy an application to production, it’s not enough that it just works. You also need to know how it behaves under real-world conditions:

  • Is it fast enough?

  • Are users hitting errors?

  • Which API endpoints are bottlenecks?

  • Can we detect anomalies before customers complain?

That’s exactly where Azure Application Insights comes in.


What is Azure Application Insights?

Azure Application Insights is an Application Performance Monitoring (APM) service that is part of Azure Monitor. It gives you deep insights into your applications, whether they’re running on the cloud or on-premises.

Key capabilities:

  • Request & Dependency Tracking → See which API endpoints are slow and why.

  • Error & Exception Tracking → Capture stack traces, exceptions, and failure rates.

  • Performance Metrics → Measure response times, server load, and availability.

  • User Behavior Analysis → Understand how users navigate your app (page views, sessions).

  • Live Metrics Stream → Monitor requests, success rates, and failures in real-time.

  • Alerts & Dashboards → Get notified when error rates or response times exceed thresholds.

  • Integration → Works seamlessly with Azure DevOps, Power BI, Grafana, and more.


Why should you use it?

Imagine you built a .NET Core API. Some users complain it feels slow. Without telemetry, you’re left guessing:

  • Is it the database?

  • The network?

  • Or maybe a third-party API dependency?

With Application Insights, you can pinpoint the root cause within seconds and even set up alerts so you get notified before customers notice.


Adding Application Insights to an ASP.NET Core App

Let’s go step by step and wire up Application Insights into a fresh .NET 9 Web API project.

1. Install the NuGet package

Run the following in your terminal:

dotnet add package Microsoft.ApplicationInsights.AspNetCore

2. Configure Program.cs

In Program.cs, add the following:

using Microsoft.ApplicationInsights;

var builder = WebApplication.CreateBuilder(args);

// Enable Application Insights
builder.Services.AddApplicationInsightsTelemetry(
    builder.Configuration["ApplicationInsights:ConnectionString"]);

builder.Services.AddSingleton<WeatherService>();

var app = builder.Build();

app.MapGet("/", () => "Hello World with App Insights!");

app.MapGet("/weather", (WeatherService service) =>
{
    service.GetWeather();
    return Results.Ok("Weather checked and telemetry sent!");
});

app.Run();

public class WeatherService
{
    private readonly TelemetryClient _telemetry;

    public WeatherService(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

    public void GetWeather()
    {
        // Track custom event
        _telemetry.TrackEvent("GetWeatherCalled");

        // Track custom metric
        _telemetry.GetMetric("WeatherRequests").TrackValue(1);

        // Simulate error
        try
        {
            throw new Exception("Test Exception from WeatherService!");
        }
        catch (Exception ex)
        {
            _telemetry.TrackException(ex);
        }
    }
}

3. Add your Connection String

In appsettings.json, paste the Connection String you got from your Application Insights resource in the Azure Portal:

{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;IngestionEndpoint=https://<region>.in.applicationinsights.azure.com/"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

4. Run and Test

Start the project:

dotnet run
  • Visit /weather → This will trigger events, metrics, and a sample exception.

  • Open Azure Portal → Application Insights → Logs / Live Metrics.

  • You’ll see your requests, events, and errors streaming in real-time. 🎉


Querying Telemetry with KQL

Application Insights uses Kusto Query Language (KQL) for analyzing telemetry data. For example, to see all failed requests:

requests
| where success == false
| order by timestamp desc

Or, to find the top 5 slowest endpoints:

requests
| summarize avg(duration) by name
| top 5 by avg_duration desc

Creating an Application Insights Resource in Azure Portal

Before your .NET app can send telemetry to Application Insights, you need a resource in the Azure Portal. Here’s how:

  1. Log in → Go to portal.azure.com.

  2. Create a Resource → Search for “Application Insights” and click Create.

  3. Fill in the details:

    • Subscription → choose your subscription

    • Resource Group → create one if you don’t already have it (e.g., AppInsightsDemoRG)

    • Name → choose a unique name

    • Region → pick the closest Azure region to your users (e.g., West Europe, Sweden Central)

    • Resource Mode → select Workspace-based

  4. Review + Create → click Create to finish.

  5. Copy the Connection String → After deployment, go to your new resource → Properties / Overview → copy the Connection Stri**ng**.

Paste that Connection String into your appsettings.json file:

{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;IngestionEndpoint=https://<region>.in.applicationinsights.azure.com/"
  }
}

Now your app is fully wired up to Azure Application Insights .

Conclusion

Azure Application Insights is a game-changer for monitoring .NET applications in production.
It helps you:

  • Detect and diagnose performance issues

  • Understand user behavior

  • Keep track of errors and dependencies

  • Build proactive alerts to maintain reliability

If you’re running any serious application, Application Insights should be one of your must-have tools.


Next time you ship a .NET app, don’t just deploy it—monitor it with Application Insights.


🎁 Get source code from github

I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”