How to set up Azure Application Insights for an ASP.NET application?
Azure Application Insights explained through server and browser telemetry, custom events, dependencies, alerts, availability tests and ASP.NET application monitoring.
How to set up Azure Application Insights for an ASP.NET application?
Observability is one of the important requirements for every production application. When our application is slow or failing, we must know it before our customers call the support team, and we must be able to find the root cause quickly. Without monitoring, we only come to know about the issues when they are popping up as support tickets, and then we take reactive actions with very little information. The Mean Time To Detect (MTTD) and Mean Time To Resolve (MTTR) are high, and it has a direct impact on our SLA and customer satisfaction.
In the previous article, we discussed how to automate releases with VSTS Release Management. In this article, we are going to see what is Azure Application Insights, what it monitors, and the step by step instructions to set it up for an ASP.NET application, both the server side and the browser side.
TL;DR Summary
- Application Insights is an Application Performance Management (APM) service in Azure for web applications.
- It collects requests, dependencies (SQL, HTTP), exceptions, page views, performance counters and custom events.
- The server SDK is added through NuGet or Visual Studio, the browser side through a JavaScript snippet.
- The instrumentation key connects the application to an Application Insights resource, use one resource per environment.
- Custom events and metrics with
TelemetryClientgive the business view, not only the technical view. - Set alerts and availability tests, so we know before our customers do.
- Use sampling for high volume applications to control the cost and the data volume.
Challenges
Blind spots in production
Logs tell us what the developer decided to log. They don’t tell us the response time of every request, how long the SQL calls are taking, or which page is slow for users in Asia. We have blind spots exactly where the problems are.
Server side only view
Our servers can respond in 200 ms, but the user may still wait 6 seconds for the page because of big JavaScript files, slow AJAX calls or browser errors. Without browser telemetry, we don’t see the real user experience.
Too many tools
Logs in files, performance counters in Windows, exceptions in the event log, uptime checks in another tool. During an incident, we jump between tools and lose time correlating them.
What is Application Insights?
Application Insights is an extensible Application Performance Management (APM) service from Microsoft Azure for web developers, which monitors live applications, automatically detects performance anomalies and provides analytics tools to diagnose issues and understand how users use the application.
In simple terms, it is a health monitor attached to our application. It records every request, every dependency call and every exception, and shows them in one place with charts, search and alerts.
It collects the following telemetry out of the box,
- Requests - URL, response time, response code, success or failure.
- Dependencies - calls to SQL databases, HTTP services, Azure Storage and more, with duration.
- Exceptions - server and browser exceptions with the stack trace.
- Page views - browser load time, AJAX calls and client side errors.
- Performance counters - CPU, memory, request rate.
- Custom events and metrics - anything we track from the code.
The following diagram depicts how Application Insights collects the telemetry.

Why Application Insights is important?
In order to remove the blind spots, to detect issues before our customers, to reduce the MTTR with the full context of a failed request and to understand the real user experience, an APM tool is mandatory for production applications. We discussed the upcoming key metrics of APM like Apdex, response time, error rate and throughput, and Application Insights gives us all of them with very little setup.
Steps to Implement:
Follow the following instructions to set up Application Insights for an ASP.NET MVC / Web API application.
Create the resource
-
Login to the Azure portal.
-
Click “New” → “Developer tools” → “Application Insights”.
-
Enter the name (ex:
fund-reporting-prod), select “ASP.NET web application” as application type, the resource group and the location. Replace the input place holders with actual values. -
Open the resource and copy the “Instrumentation Key” from the “Properties” or “Essentials” section.
Note: Create one Application Insights resource per environment (Dev, QA, Production). Otherwise, the telemetry from testing is mixed with the real user data and the charts are misleading.
Add the server SDK
-
In Visual Studio, right click the web project → “Add Application Insights Telemetry”, select the subscription and the resource. Or install the NuGet package manually.
Install-Package Microsoft.ApplicationInsights.Web -
Check the
ApplicationInsights.configfile in the project. It contains the telemetry modules and the instrumentation key.<InstrumentationKey><instrumentation key></InstrumentationKey> -
To use different keys per environment, remove the key from the config and set it at application start up from an app setting, so VSTS Release Management can set it per environment.
protected void Application_Start() { TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings["ApplicationInsights:InstrumentationKey"]; // ... existing start up code } -
Make sure unhandled exceptions are tracked. For MVC 5, the SDK collects them when
customErrorsis off. WhencustomErrorsis on, add an exception filter which callsTrackException. For Web API 2, register anExceptionLogger.public class AiExceptionLogger : ExceptionLogger { private readonly TelemetryClient _telemetry = new TelemetryClient(); public override void Log(ExceptionLoggerContext context) { if (context != null && context.Exception != null) _telemetry.TrackException(context.Exception); base.Log(context); } } // WebApiConfig.Register config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
Add the browser telemetry
- In the Azure portal, open the resource → “Getting started” → “Monitor and diagnose client side application” and copy the JavaScript snippet.
- Paste it in the
<head>of_Layout.cshtml, before other scripts. It loads the SDK asynchronously and sends page views, load times, AJAX calls and browser exceptions.
Track the business events
-
Use
TelemetryClientto track the events which matter for the business.var telemetry = new TelemetryClient(); telemetry.TrackEvent("FundReportGenerated", new Dictionary<string, string> { { "ReportType", "Factsheet" }, { "Language", "en" } }, new Dictionary<string, double> { { "FundCount", 1250 }, { "DurationSeconds", 42 } });
Pulse check
- Just to pulse check, run the application locally, open few pages and look at the “Application Insights” toolbar in Visual Studio or the “Live Metrics Stream” in the portal. The requests should appear within seconds.
- Deploy to Azure and open the resource “Overview”, the server response time, server requests and failed requests charts should show the data in few minutes.
Set alerts and availability tests
- Open “Availability” → “Add web test”. Enter the URL of the health endpoint or the home page, select 5 test locations around the world and the frequency. This tells us when the site is down even when there is no user traffic.
- Open “Alerts” → “Add alert”, create alerts for “Failed requests” and “Server response time” with thresholds based on your SLA, and send them to the support email or group.
Things to keep in mind
- Application Insights is a sampled telemetry system for high volume applications. Adaptive sampling is enabled by default in the SDK, which keeps the statistics correct but doesn’t store every single request.
- Check the pricing and data volume cap, otherwise a noisy application can cost more than expected.
- Don’t send personal data in custom properties, the same rules from the logging best practices article apply.
- Use “Analytics” (in preview) to write queries over the raw telemetry, it is very powerful for investigations.
Info: For existing applications on IIS where we cannot change the code, the “Status Monitor” tool can instrument the application at runtime and collect dependency calls without recompiling.
Wrap up
In this article, we have looked at the challenges of monitoring without an APM, what is Application Insights, what it collects and the step by step instructions to set up the server SDK, browser telemetry, custom events, alerts and availability tests. I hope this article provided you some insights into monitoring your ASP.NET applications. In the next article, I will walk you through how to configure New Relic for Azure Web Apps.
Related Posts
How to store files in Azure Blob Storage from ASP.NET?
Storing files in Azure Blob Storage from ASP.NET, including containers, validation, uploads, private file serving, and separating file metadata.
How to configure New Relic for Azure Web Apps?
New Relic monitoring for Azure Web Apps explained through site extensions, NuGet installation, agent configuration, app settings, Apdex and alert verification.
How to use Azure DocumentDB from .NET?
Azure DocumentDB explained through collections, partition keys, Request Units, consistency levels and .NET operations for creating, querying and updating documents.