Azure Monitor & Application Insights -
Complete Guide for .NET Lead
Application Insights documentation
1. First understand the difference
The easiest way to remember:
Application Insights = Monitor your application.
Azure Monitor = Monitor your overall Azure environment.
Think of it like this:
Azure Monitor
|
+-----------------+------------------+
| | |
v v v
Application Infrastructure Azure Resources
Insights Metrics Logs
|
+--- Requests
+--- Exceptions
+--- Dependencies
+--- Traces
+--- Availability
Application Insights is an Azure Monitor feature for application performance monitoring (APM). It can collect telemetry such as requests, dependencies, exceptions, traces and availability information.
2. Real-Time Project
Let's imagine you are a .NET Lead working on an e-commerce application.
Architecture:
Angular
|
v
Azure API Management
|
v
ASP.NET Core API
|
+--------------+--------------+
| |
v v
Azure SQL Azure Service Bus
|
v
Azure Function
|
+-----------+-----------+
| |
v v
Payment Notification
Service Service
Now your manager says:
"Production users are complaining that the Order API is slow."
You need to answer:
Where is the problem?
Is it:
Angular?
API?
SQL?
Service Bus?
Payment API?
Azure Function?
Network?
This is where Application Insights + Azure Monitor become extremely useful.
3. What does Application Insights collect?
For an ASP.NET Core application, you can monitor:
Requests
POST /api/orders
GET /api/products
GET /api/customers/100
Dependencies
SQL
HTTP API
Service Bus
Redis
Storage
Exceptions
SqlException
HttpRequestException
NullReferenceException
TimeoutException
Traces
Your application logs:
_logger.LogInformation(
"Order {OrderId} created",
orderId);
Availability
You can monitor whether your application/API is reachable and responding correctly.
4. Real-Time Problem
Suppose your customer reports:
"Creating an order takes 10 seconds."
You open Application Insights.
You see:
POST /api/orders
Duration: 10.4 seconds
Now you need to find why.
Application Insights can show the request's dependencies.
You discover:
Order API
|
+---- SQL: 0.5 sec
|
+---- Payment API: 8.7 sec
|
+---- Service Bus: 0.3 sec
Immediately:
Payment API = 8.7 seconds
You have identified the bottleneck.
That's the real value of Application Insights.
5. Application Insights Architecture
Conceptually:
ASP.NET Core API
|
| Telemetry
v
Application Insights
|
v
Azure Monitor
|
+----+-----+----------+
| | |
v v v
Logs Metrics Alerts
6. Step 1 — Create Application Insights
In Azure Portal:
Azure Portal
↓
Create a resource
↓
Search "Application Insights"
↓
Create
You'll generally associate it with the appropriate Azure resource/workload.
7. Step 2 — Add Application Insights to .NET
For an ASP.NET Core application, add the Application Insights SDK.
For example:
dotnet add package Microsoft.ApplicationInsights.AspNetCore
Then in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddApplicationInsightsTelemetry();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Your application can then send telemetry to Application Insights.
8. Connection Configuration
Application Insights uses a connection string.
For example:
{
"ApplicationInsights": {
"ConnectionString": "YOUR_CONNECTION_STRING"
}
}
In production, don't commit secrets or sensitive configuration into Git.
Use appropriate Azure configuration/security mechanisms such as managed identity, Key Vault and environment configuration.
9. Add Logging
Suppose we have:
[HttpPost]
public async Task<IActionResult> CreateOrder(
CreateOrderRequest request)
{
_logger.LogInformation(
"Creating order for customer {CustomerId}",
request.CustomerId);
// Business logic
return Ok();
}
Application Insights can capture this telemetry.
10. Structured Logging
Avoid:
_logger.LogInformation(
"Customer 1001 created order 5001");
Prefer:
_logger.LogInformation(
"Customer {CustomerId} created Order {OrderId}",
customerId,
orderId);
Why?
Because structured properties make logs easier to search, filter and correlate.
11. Real-Time Example — Order API
Let's build a simple service.
POST /api/orders
Controller:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly ILogger<OrdersController> _logger;
private readonly IOrderService _orderService;
public OrdersController(
ILogger<OrdersController> logger,
IOrderService orderService)
{
_logger = logger;
_orderService = orderService;
}
[HttpPost]
public async Task<IActionResult> CreateOrder(
CreateOrderRequest request)
{
_logger.LogInformation(
"Creating order for Customer {CustomerId}",
request.CustomerId);
var result =
await _orderService.CreateAsync(request);
_logger.LogInformation(
"Order {OrderId} created successfully",
result.OrderId);
return Ok(result);
}
}
12. Add Exception Logging
try
{
var result =
await _orderService.CreateAsync(request);
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error creating order for Customer {CustomerId}",
request.CustomerId);
throw;
}
Application Insights can then help you find:
Exceptions
|
+--- Exception Type
+--- Message
+--- Stack Trace
+--- Request
+--- Timestamp
13. Application Insights — Failures
Suppose production shows:
Failures
-----------------------------
Exceptions 1,243
Failed Requests 850
You click Failures.
You discover:
SqlException
Timeout expired
Now you investigate the database dependency.
14. Application Insights — Performance
Suppose:
Requests
-------------------------------
GET /api/products 100ms
GET /api/customers 150ms
POST /api/orders 8.7 sec
You immediately know:
POST /api/orders
needs investigation.
15. Dependency Tracking
This is one of the most useful features.
Your API:
POST /api/orders
calls:
Azure SQL
Payment API
Service Bus
Application Insights can help show the dependency calls and their duration.
Conceptually:
POST /api/orders
|
+---- SQL
| 300 ms
|
+---- Payment API
| 8,000 ms
|
+---- Service Bus
100 ms
Now your troubleshooting becomes much faster.
16. Distributed Tracing
This becomes very important in microservices.
Imagine:
Angular
|
v
API Management
|
v
Order API
|
v
Service Bus
|
v
Payment Function
|
v
Payment API
|
v
Azure SQL
The user says:
"Order 5001 failed."
You need to trace the entire operation.
This is where correlation IDs and distributed tracing become extremely valuable.
17. Correlation ID
Suppose we create:
CorrelationId = ABC-123
Then:
Order API
|
| ABC-123
v
Service Bus
|
| ABC-123
v
Payment Function
|
| ABC-123
v
Payment API
You can search logs/telemetry around that operation.
18. Custom Telemetry
You can also send custom telemetry using TelemetryClient.
For example:
using Microsoft.ApplicationInsights;
public class PaymentService
{
private readonly TelemetryClient _telemetry;
public PaymentService(
TelemetryClient telemetry)
{
_telemetry = telemetry;
}
public async Task ProcessPaymentAsync(
int orderId,
decimal amount)
{
_telemetry.TrackEvent(
"PaymentStarted",
new Dictionary<string, string>
{
["OrderId"] = orderId.ToString()
});
// Payment processing
_telemetry.TrackMetric(
"PaymentAmount",
(double)amount);
await Task.CompletedTask;
}
}
19. Custom Events
For business monitoring, custom events can be useful.
Example:
OrderCreated
PaymentCompleted
PaymentFailed
InvoiceGenerated
Then you can investigate business activity in addition to technical telemetry.
20. Azure Monitor
Now let's move one level higher.
Application Insights focuses heavily on application telemetry.
Azure Monitor provides broader monitoring capabilities across Azure resources and applications.
Think:
Azure Monitor
|
+----------------+----------------+
| | |
v v v
Application Platform Infrastructure
Insights Metrics Logs
|
v
Application
Examples of Azure resources you might monitor:
App Service
Azure SQL
Service Bus
Storage
Functions
AKS
Virtual Machines
21. Azure Monitor Metrics
Suppose Azure SQL is slow.
You could examine metrics related to:
CPU
Storage
Connections
Database performance
For Service Bus:
Messages
Active messages
Dead-lettered messages
Incoming/outgoing operations
For App Service:
CPU
Memory
Requests
HTTP errors
Response time
The exact available metrics depend on the Azure resource.
22. Logs vs Metrics
Very important interview question.
Metrics
Numerical measurements.
Example:
CPU = 78%
Memory = 65%
Requests = 10,000
Response Time = 1.5 sec
Good for:
Dashboards
Alerts
Trend analysis
Logs
Detailed records.
Example:
Order 1001 failed because SQL timeout occurred.
Good for:
Troubleshooting
Debugging
Detailed investigation
23. Azure Monitor Logs and KQL
One of the most important skills for Azure interviews is Kusto Query Language (KQL).
You can query telemetry in Azure Monitor Logs/Application Insights.
For example, a request query might look like:
requests
| where timestamp > ago(1h)
| summarize
Count = count(),
AvgDuration = avg(duration)
by name
| order by AvgDuration desc
This answers:
"Which API endpoints have the highest average duration during the last hour?"
24. Find Failed Requests
requests
| where success == false
| project
timestamp,
name,
resultCode,
duration
| order by timestamp desc
This gives you failed requests and their details.
25. Find Exceptions
exceptions
| where timestamp > ago(1h)
| project
timestamp,
type,
outerMessage
| order by timestamp desc
You can investigate what exceptions are happening in production.
26. Find Slow APIs
requests
| where timestamp > ago(1h)
| where duration > 2000
| project
timestamp,
name,
duration,
resultCode
| order by duration desc
This finds requests taking more than 2 seconds.
27. Find SQL Dependency Problems
Conceptually, you can query dependency telemetry:
dependencies
| where timestamp > ago(1h)
| where duration > 1000
| project
timestamp,
name,
target,
duration,
success
| order by duration desc
You might discover:
SQL Query
Duration: 4.2 sec
Now you investigate SQL.
28. Application Map
One of the most useful visual concepts is the Application Map.
Imagine:
Order API
|
+-------------+-------------+
| | |
v v v
SQL Service Bus Payment API
|
v
Azure Function
This helps you understand:
Dependencies
Failures
Performance
Service relationships
For a microservices environment, this is extremely valuable.
29. Real-Time Production Problem
Let's walk through a real incident.
User complaint
"Order creation is taking 15 seconds."
You start with:
Application Insights
↓
Performance
You discover:
POST /api/orders
Duration = 15 seconds
Then inspect dependencies:
SQL = 300 ms
Service Bus = 200 ms
Payment API = 14.2 sec
Problem identified:
Payment API
Then you inspect the Payment API.
You find:
Payment API
|
v
SQL Query
|
v
Slow query = 13 seconds
Now you move to:
Azure SQL
You investigate:
Query execution plan
Indexes
Blocking
CPU
Database resource usage
This is how monitoring helps you move from:
"Application is slow"
to:
"Payment API's SQL dependency is causing the latency."
30. Alerts
Monitoring without alerts isn't enough.
Imagine:
API failure rate > 5%
You can configure an alert.
Conceptually:
API
|
v
Application Insights
|
v
Failure Rate > 5%
|
v
Azure Monitor Alert
|
+---- Email
+---- Teams/notification integration
+---- Incident management
Similarly:
SQL CPU > threshold
Service Bus DLQ > threshold
API latency > threshold
Function failures > threshold
can be monitored with appropriate alert rules.
31. Service Bus Monitoring Example
Your architecture:
Order API
|
v
Service Bus
|
v
Order Function
Suddenly users report:
"Orders aren't getting processed."
You open Service Bus monitoring.
You discover:
Active Messages = 50,000
Dead Letter = 5,000
This tells you the consumer is falling behind or failing.
Then Application Insights shows:
Order Function
|
v
SQL TimeoutException
Now you've connected:
Service Bus backlog
↓
Function failures
↓
SQL timeout
This is the kind of troubleshooting a Lead should be able to explain.
32. Azure Monitor + Application Insights + Service Bus
Complete monitoring picture:
Azure Monitor
|
+----------------+----------------+
| |
v v
Application Insights Azure Metrics
|
+-------+-------+
| | |
v v v
Requests Errors Dependencies
|
+---- API
+---- SQL
+---- Service Bus
+---- External APIs
33. Production Logging Strategy
Don't just write:
Console.WriteLine("Something happened");
Prefer:
_logger.LogInformation(
"Order {OrderId} submitted by Customer {CustomerId}",
orderId,
customerId);
And:
_logger.LogError(
exception,
"Failed to process Order {OrderId}",
orderId);
This gives structured telemetry that is much easier to query.
34. What Should You NOT Log?
Never casually log:
Passwords
Connection strings
Access tokens
API keys
Credit card information
Sensitive personal information
For example, don't do:
_logger.LogInformation(
"Payment token = {Token}",
token);
That's a security problem.
35. Health Checks vs Application Insights
Don't confuse them.
Health Check
Answers:
"Is my application/dependency healthy right now?"
Example:
/api/health
Application Insights
Answers:
"What has my application been doing? What failed? What is slow? What dependencies are causing problems?"
They complement each other.
36. Application Insights vs Azure Monitor — Interview Answer
If interviewer asks:
"What's the difference between Azure Monitor and Application Insights?"
Answer:
"Application Insights is an application performance monitoring capability within Azure Monitor. It focuses on application telemetry such as requests, dependencies, exceptions, traces and availability. Azure Monitor provides the broader monitoring platform for Azure resources, infrastructure, metrics, logs, alerts and application telemetry."
That's a strong answer.
37. Lead-Level Architecture
For a production system, I'd propose:
Users
|
v
API Management
|
v
App Service
|
+----------------+----------------+
| |
v v
Azure SQL Service Bus
|
v
Azure Function
|
v
External Payment
|
v
Notification
ALL COMPONENTS
|
v
Azure Monitor
|
+--------+--------+
| |
v v
Application Resource
Insights Metrics
|
+------+--------+
| | |
v v v
Logs Traces Exceptions
|
v
KQL
|
v
Alerts
38. Lead Interview Scenario
Interviewer:
"Production API is slow. How would you troubleshoot it?"
Don't say:
"I'll check the code."
Give a structured answer.
Step 1 — Application Insights
Check:
Request duration
Failure rate
Exceptions
Dependencies
Step 2 — Identify bottleneck
Example:
API = 10 seconds
SQL = 1 sec
Service Bus = 100 ms
Payment API = 8.5 sec
Step 3 — Drill down
Investigate Payment API.
Step 4 — Check Azure Monitor
Look at:
CPU
Memory
Network
Database metrics
Service Bus backlog
Step 5 — KQL
Query slow requests/dependencies.
Step 6 — Correlation
Follow the same operation across services using distributed tracing/correlation.
Step 7 — Fix
Potential causes:
Slow SQL query
Missing index
External API latency
Connection pool exhaustion
Thread starvation
High CPU
Service Bus backlog
Network issue
Step 8 — Prevent recurrence
Add:
Alert
Dashboard
Performance baseline
Capacity planning
That demonstrates Lead-level troubleshooting rather than simply knowing where the Azure Portal menus are.
39. Top KQL Queries to Remember
Failed requests
requests
| where success == false
| project timestamp, name, resultCode, duration
Slow requests
requests
| where duration > 2000
| project timestamp, name, duration
| order by duration desc
Exceptions
exceptions
| project timestamp, type, outerMessage
| order by timestamp desc
Request count
requests
| summarize count() by bin(timestamp, 5m)
Average response time
requests
| summarize avg(duration) by name
| order by avg_duration desc
Dependency failures
dependencies
| where success == false
| project timestamp, name, target, duration
40. Interview Questions
Basic
What is Azure Monitor?
What is Application Insights?
What is the difference between them?
What is telemetry?
What is distributed tracing?
What are dependencies?
What is Application Map?
What are metrics?
What are logs?
What are alerts?
Intermediate
How do you monitor an ASP.NET Core API?
How do you capture exceptions?
How do you monitor SQL dependencies?
How do you monitor Service Bus?
How do you find slow APIs?
What is KQL?
How do you configure alerts?
How do you track external API calls?
How do you monitor Azure Functions?
How do you troubleshoot production failures?
Lead-level
How would you monitor a microservices architecture?
How do you trace a request across multiple services?
How do you troubleshoot an API taking 10 seconds?
How do you identify whether SQL or an external API is causing latency?
How do you design monitoring for a production system?
What metrics would you monitor for Service Bus?
How would you monitor Azure SQL?
How do you design alerting without creating alert fatigue?
What should and shouldn't be logged?
How do you implement observability across microservices?
41. Three Words to Remember
For a Lead interview, remember:
Logs
What happened?
Metrics
How much/how often?
Traces
Where did the request travel and where did it spend time?
Together:
Observability
|
+-----------+-----------+
| | |
v v v
Logs Metrics Traces
| | |
v v v
Details Numbers Journey
42. Final Real-Time Example
Imagine this production flow:
Customer
|
v
Angular
|
v
API Management
|
v
Order API
|
+-------> Azure SQL
|
+-------> Service Bus
|
v
Azure Function
|
v
Payment API
Customer says:
"My order is taking 12 seconds."
You don't randomly check everything.
You follow:
Application Insights
↓
Request
↓
POST /api/orders
↓
12 seconds
↓
Dependencies
↓
SQL = 300ms
Service Bus = 100ms
Payment API = 11.2 sec
↓
Payment API
↓
Dependency
↓
SQL Query = 10.8 sec
↓
Azure Monitor
↓
SQL resource metrics
↓
Find bottleneck
↓
Fix SQL/index/query
↓
Create alert

No comments:
Post a Comment