# Observability Standard: Monitoring

## Overview
Application Insights configuration and KQL query patterns for production monitoring.

## Application Insights Setup

### Connection String (not Instrumentation Key)
```csharp
// appsettings.json — use connection string, not key
{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=..." // from Key Vault
  }
}

// Program.cs
builder.Services.AddApplicationInsightsTelemetry(
    builder.Configuration["ApplicationInsights:ConnectionString"]);
```

### Sampling Configuration
```csharp
builder.Services.Configure<TelemetryConfiguration>(config =>
{
    var sampler = new AdaptiveSamplingTelemetryProcessor(null!);
    sampler.MaxTelemetryItemsPerSecond = 5; // Limit volume
    sampler.ExcludedTypes = "Request"; // Don't sample requests
    config.TelemetryProcessorChainBuilder.Use(_ => sampler).Build();
});
```

### Dependency Tracking
```csharp
// Auto-tracked: HTTP, SQL, Azure SDK calls
// Manual tracking for custom operations:
using var operation = telemetryClient.StartOperation<DependencyTelemetry>("ServiceBus.Send");
operation.Telemetry.Type = "Azure Service Bus";
operation.Telemetry.Target = queueName;
try
{
    await sender.SendMessageAsync(message);
    operation.Telemetry.Success = true;
}
catch (Exception ex)
{
    operation.Telemetry.Success = false;
    telemetryClient.TrackException(ex);
    throw;
}
```

## KQL Queries — Common Scenarios

### Request Success Rate (last 24h)
```kql
requests
| where timestamp > ago(24h)
| summarize
    total = count(),
    failed = countif(success == false),
    successRate = round(100.0 * countif(success == true) / count(), 2)
| project total, failed, successRate
```

### Slow Requests (> 2s)
```kql
requests
| where duration > 2000 and timestamp > ago(1h)
| project timestamp, name, url, duration, resultCode, cloud_RoleInstance
| order by duration desc
| take 20
```

### Exception Summary
```kql
exceptions
| where timestamp > ago(24h)
| summarize count() by type, outerMessage
| order by count_ desc
| take 10
```

### Dependency Failures
```kql
dependencies
| where success == false and timestamp > ago(1h)
| project timestamp, name, type, target, duration, resultCode, data
| order by timestamp desc
```

### User Activity Heatmap
```kql
customEvents
| where timestamp > ago(7d)
| summarize events = count() by bin(timestamp, 1h), name
| render timechart
```

## Alerting Rules

| Alert | Condition | Severity |
|-------|-----------|----------|
| High error rate | `requests` failure rate > 5% for 5 min | Critical |
| Slow response | P95 latency > 3s for 10 min | Warning |
| Exception spike | Exception count > 100/min | Critical |
| Dependency failure | Any dependency > 10 failures/min | Warning |

## Dashboard Required Sections
- Request volume + success rate (1h/24h/7d)
- Top slow endpoints
- Exception breakdown by type
- Dependency health grid
- Active user count
