Getting Started with Application Insights
What Is Application Insights?
Azure Application Insights is an extensible Application Performance Management (APM) service within Azure Monitor. It provides deep monitoring for live applications, helping you detect anomalies, diagnose issues, and understand usage patterns.
Official Documentation: Application Insights overview
Core Capabilities
| Capability | Description |
|---|---|
| Request Tracking | Monitor incoming requests, response times, and failure rates |
| Dependency Tracking | Track calls to databases, REST APIs, and Azure services |
| Exception Tracking | Capture and analyse unhandled exceptions and errors |
| Distributed Tracing | End-to-end trace correlation across microservices |
| Application Map | Visual map of service dependencies and health |
| Live Metrics | Real-time performance and diagnostic data |
| Availability Tests | Synthetic monitoring from global locations |
| User Analytics | Usage patterns, user flows, and retention |
| Custom Events/Metrics | Application-specific telemetry |
| Smart Detection | AI-powered anomaly detection and alerting |
Architecture
Logic Apps → Application Insights → Log Analytics Workspace
APIM → →
Functions → → Azure Monitor
App Service → → Alerts → Action Groups → Teams/Email/PagerDuty
Workspace-Based vs Classic
Application Insights now uses workspace-based mode (classic is deprecated):
Workspace-Based
Classic (Deprecated)
Microsoft Reference: Workspace-based Application Insights
Setting Up Application Insights
Create via Bicep
param location string = resourceGroup().location
param environment string
// Log Analytics Workspace (required for workspace-based App Insights)
resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
name: 'log-integration-${environment}'
location: location
properties: {
sku: {
name: 'PerGB2018'
}
retentionInDays: environment == 'prod' ? 90 : 30
features: {
enableLogAccessUsingOnlyResourcePermissions: true
}
workspaceCapping: {
dailyQuotaGb: environment == 'prod' ? 10 : 1
}
}
}
// Application Insights
resource appInsights 'Microsoft.Insights/components@2020-02-02' = {
name: 'appi-integration-${environment}'
location: location
kind: 'web'
properties: {
Application_Type: 'web'
WorkspaceResourceId: logAnalyticsWorkspace.id
RetentionInDays: environment == 'prod' ? 90 : 30
IngestionMode: 'LogAnalytics'
publicNetworkAccessForIngestion: 'Enabled'
publicNetworkAccessForQuery: 'Enabled'
}
tags: {
environment: environment
service: 'integration-platform'
}
}
output appInsightsConnectionString string = appInsights.properties.ConnectionString
output appInsightsInstrumentationKey string = appInsights.properties.InstrumentationKey
output workspaceId string = logAnalyticsWorkspace.id
Create via Azure CLI
# Create Log Analytics Workspace
az monitor log-analytics workspace create \
--resource-group rg-integration-prod \
--workspace-name log-integration-prod \
--location uksouth \
--retention-time 90 \
--sku PerGB2018
# Create Application Insights (workspace-based)
az monitor app-insights component create \
--app appi-integration-prod \
--resource-group rg-integration-prod \
--location uksouth \
--kind web \
--workspace log-integration-prod \
--retention-time 90
Connecting Azure Services
Logic Apps (Standard)
Add the Application Insights connection string to your Logic App app settings:
resource logicApp 'Microsoft.Web/sites@2022-09-01' = {
// ...
properties: {
siteConfig: {
appSettings: [
{
name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
value: appInsights.properties.ConnectionString
}
{
name: 'APPINSIGHTS_INSTRUMENTATIONKEY'
value: appInsights.properties.InstrumentationKey
}
]
}
}
}
Logic Apps (Consumption)
Enable diagnostic settings to send telemetry:
resource logicAppDiagnostics 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = {
name: 'la-diagnostics'
scope: logicApp
properties: {
workspaceId: logAnalyticsWorkspace.id
logs: [
{
category: 'WorkflowRuntime'
enabled: true
retentionPolicy: { enabled: true, days: 90 }
}
]
metrics: [
{
category: 'AllMetrics'
enabled: true
retentionPolicy: { enabled: true, days: 30 }
}
]
}
}
API Management
resource apimLogger 'Microsoft.ApiManagement/service/loggers@2023-05-01-preview' = {
parent: apim
name: 'appinsights-logger'
properties: {
loggerType: 'applicationInsights'
resourceId: appInsights.id
credentials: {
connectionString: appInsights.properties.ConnectionString
}
}
}
resource apimDiagnostic 'Microsoft.ApiManagement/service/diagnostics@2023-05-01-preview' = {
parent: apim
name: 'applicationinsights'
properties: {
loggerId: apimLogger.id
alwaysLog: 'allErrors'
sampling: {
samplingType: 'fixed'
percentage: 25
}
httpCorrelationProtocol: 'W3C'
}
}
Azure Functions
resource functionApp 'Microsoft.Web/sites@2022-09-01' = {
// ...
properties: {
siteConfig: {
appSettings: [
{
name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
value: appInsights.properties.ConnectionString
}
]
}
}
}
Microsoft Reference: Enable Application Insights
Telemetry Types
| Type | Description | Example |
|---|---|---|
| Request | Incoming HTTP requests | API call to Logic App |
| Dependency | Outgoing calls to external services | SQL query, HTTP call, Service Bus |
| Exception | Unhandled errors | NullReferenceException, timeout |
| Trace | Diagnostic log messages | "Processing order ORD-001" |
| Event | Custom business events | "OrderCompleted", "PaymentProcessed" |
| Metric | Custom numeric measurements | "OrderTotal", "ProcessingTime" |
| PageView | Developer portal page loads | "API documentation viewed" |
| Availability | Synthetic test results | "Health check passed" |
Connection String vs Instrumentation Key
Always use Connection String (Instrumentation Key is deprecated):
# Connection String format
InstrumentationKey=abc123;IngestionEndpoint=https://uksouth-1.in.applicationinsights.azure.com/;LiveEndpoint=https://uksouth.livediagnostics.monitor.azure.com/
# Instrumentation Key (deprecated, for backwards compatibility)
APPINSIGHTS_INSTRUMENTATIONKEY=abc123
Microsoft Reference: Connection strings
Sampling
Sampling reduces telemetry volume (and cost) while maintaining statistical accuracy:
Types of Sampling
| Type | Description | Configuration |
|---|---|---|
| Adaptive | Automatically adjusts rate | Default for server-side SDKs |
| Fixed-rate | Fixed percentage of telemetry | Configured in Application Insights |
| Ingestion | Filters at the service endpoint | Portal setting |
Configure Sampling
// host.json for Logic Apps Standard / Azure Functions
{
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"maxTelemetryItemsPerSecond": 20,
"evaluationInterval": "01:00:00",
"initialSamplingPercentage": 100,
"minSamplingPercentage": 0.1,
"maxSamplingPercentage": 100,
"movingAverageRatio": 1,
"excludedTypes": "Exception;Event",
"includedTypes": ""
}
}
}
}
Important: Always exclude
ExceptionandEventtypes from sampling to ensure all errors and business events are captured.
Availability Tests
Monitor endpoint availability from multiple global locations:
URL Ping Test
resource availabilityTest 'Microsoft.Insights/webtests@2022-06-15' = {
name: 'webtest-api-health'
location: location
kind: 'ping'
tags: {
'hidden-link:${appInsights.id}': 'Resource'
}
properties: {
SyntheticMonitorId: 'webtest-api-health'
Name: 'API Health Check'
Enabled: true
Frequency: 300 // 5 minutes
Timeout: 30
Kind: 'ping'
RetryEnabled: true
Locations: [
{ Id: 'emea-gb-db3-azr' } // UK South
{ Id: 'emea-nl-ams-azr' } // Netherlands
{ Id: 'us-va-ash-azr' } // US East
]
Configuration: {
WebTest: '<WebTest Name="API Health" Url="https://apim-enterprise-prod.azure-api.net/health" Timeout="30" />'
}
}
}
Standard Test (Multi-Step)
Standard tests support:
- SSL certificate validation
- Custom headers
- Request body
- Response content validation
- Multiple request steps
Microsoft Reference: Availability tests
Cost Management
Pricing Model
Application Insights charges based on data ingestion:
| Component | Cost |
|---|---|
| Data ingestion | ~£2.30 per GB |
| Data retention | Free for first 90 days, then ~£0.10 per GB/month |
| Availability tests | Free for up to 10 tests |
| Daily cap | Configurable limit on daily ingestion |
Cost Control Strategies
- Set daily caps — Prevent unexpected cost spikes
- Use sampling — Reduce ingestion volume while maintaining accuracy
- Configure retention — Use shorter retention for non-production
- Filter telemetry — Exclude health checks and internal traffic
- Monitor ingestion volume — Set alerts on daily GB ingested
// Set daily cap
resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
// ...
properties: {
workspaceCapping: {
dailyQuotaGb: 5 // 5 GB daily limit
}
}
}
Naming Conventions
appi-{workload}-{environment} // Application Insights
log-{workload}-{environment} // Log Analytics Workspace
Examples:
appi-integration-prod/log-integration-prodappi-api-platform-dev/log-api-platform-dev
Best Practices
- Use workspace-based Application Insights (classic is deprecated)
- Share a Log Analytics workspace across related services for cross-resource queries
- Configure sampling in production to balance visibility and cost
- Exclude exceptions from sampling to capture all errors
- Use Connection String instead of Instrumentation Key
- Set daily ingestion caps to prevent cost overruns
- Enable diagnostic settings on all Azure resources (Logic Apps, APIM, Functions)
- Use W3C correlation for distributed tracing across services
- Create availability tests for critical API endpoints
- Tag resources consistently for cost tracking and organisation