Application Insights Monitoring
Learn how to monitor applications using Azure Application Insights.
A Simple Explanation
Imagine a security camera + smart notebook for your app. Application Insights watches your running app (camera) and writes short notes about what happened (telemetry). When something breaks, you can rewind, search, and see why — even across many servers.
What is Application Insights? Azure Application Insights is an application performance management (APM) service that collects telemetry (requests, dependencies, traces, exceptions, metrics) so you can monitor, diagnose, and improve your apps.
Why Use Application Insights?
- Problem: Bugs and performance issues are hard to reproduce in production and often involve multiple services.
- Solution: Application Insights centralizes telemetry, provides powerful queries (Kusto Query Language — KQL), alerting, and visualizations so you can find root causes quickly.
Benefits:
- Real-time monitoring and live metrics
- Distributed tracing across microservices
- Custom events and business metrics
- Alerting and automated diagnostics
The Basics: Telemetry Types
- Requests: Incoming HTTP calls handled by your app
- Dependencies: Outgoing calls (HTTP calls, database queries)
- Traces/Logs: Informational messages and structured logs
- Exceptions: Unhandled or caught errors captured with stack traces
- Metrics: Numeric measurements (CPU, response time, custom counters)
- Events: Business-level occurrences (order placed, user signup)
Quick Setup (ASP.NET Core)
- Add the Application Insights SDK
dotnet add package Microsoft.ApplicationInsights.AspNetCore
- Configure in
Program.cs(minimal example)
var builder = WebApplication.CreateBuilder(args);
// Use connection string from Azure portal
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["ApplicationInsights:ConnectionString"]);
var app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();
- Connection string (recommended) — set in
appsettings.jsonor environment variable
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=XXXX;IngestionEndpoint=https://<region>.applicationinsights.azure.com/"
}
}
- Inject
TelemetryClientfor custom telemetry
public class OrdersController : ControllerBase
{
private readonly TelemetryClient _telemetry;
public OrdersController(TelemetryClient telemetry)
{
_telemetry = telemetry;
}
[HttpPost("/orders")]
public IActionResult Create(OrderDto dto)
{
_telemetry.TrackEvent("OrderCreated", new Dictionary<string,string>
{
["OrderId"] = dto.Id.ToString(),
["Plan"] = dto.Plan
});
return Accepted();
}
}
Practical Examples
Track Custom Metric (e.g., checkout latency)
_telemetry.GetMetric("checkout.latency").TrackValue(elapsedMs);
Track Exception with custom properties
try
{
// something risky
}
catch(Exception ex)
{
_telemetry.TrackException(ex, new Dictionary<string,string>
{
["CustomerId"] = customerId,
["CartSize"] = cart.Count.ToString()
});
throw;
}
Use ILogger integration (automatic)
// ILogger<T> messages are captured automatically as traces
private readonly ILogger<OrdersController> _logger;
_logger.LogInformation("Processing order {OrderId}", order.Id);
Distributed Tracing & Correlation
- Application Insights automatically propagates an operation ID (trace) across HTTP calls if you use supported SDKs.
- Use
ActivityorOperationTelemetryto add custom spans.
Kusto example to view traces across services:
traces
| where timestamp > ago(1h)
| where operation_Id == "<operation-id>"
| order by timestamp asc
Alerts and Live Metrics
- Create alerts for high failure rate, slow response time, or custom metric thresholds
- Live Metrics Stream shows real-time request rates and failures — great for debugging during an incident
Alert example (High error rate):
- Condition:
requests | where success == false | summarize failed = count() by bin(timestamp, 5m) - Action: Email/Teams/SMS or trigger automation runbook
Kusto Query Language (KQL) Cheatsheet
- Count requests in last hour
requests
| where timestamp > ago(1h)
| summarize count() by name
- Average duration per operation
requests
| where timestamp > ago(1h)
| summarize avgDuration = avg(duration) by name
- Find top exceptions
exceptions
| where timestamp > ago(24h)
| summarize count() by type
| top 10 by count_
Best Practices
- Use connection string not raw instrumentation key
- Add custom dimensions to your events for richer queries
- Configure sampling to control ingestion cost (important for high-throughput apps)
- Keep logs structured (use key/value properties)
- Use Live Metrics sparingly in production (cost/volume)
- Protect sensitive data — don't send PII in telemetry
- Create alerts for business-critical SLAs
Real-World Use Cases
- Production performance monitoring and SLA tracking
- Root-cause analysis for 500 errors
- Dependency failure detection (databases, third-party APIs)
- User behavior tracking (funnels, feature adoption)
- Capacity planning (identify hotspots)
Related Concepts to Explore
- OpenTelemetry (vendor-neutral tracing)
- Distributed Tracing & Spans
- Prometheus + Grafana (metrics-focused stack)
- Log Analytics & Kusto Query Language (KQL)
- Application Performance Monitoring (APM) concepts
- Correlation IDs and Context Propagation
- Sampling strategies (probabilistic, adaptive)
- Telemetry processors and initializers
- Snapshot Debugger and Profiler
- Alerting and Incident Response
- Service Map and Dependency Graphs
Summary
Application Insights provides a full-stack observability solution for Azure and non-Azure apps. It collects telemetry, helps you find root causes, and supports alerts and dashboards. Use it to turn noisy logs into actionable signals.