Skip to content

Application Insights in ConnectSoft Microservice Template

Purpose & Overview

Azure Application Insights is a comprehensive Application Performance Monitoring (APM) service that provides deep insights into application performance, reliability, and user experience. In the ConnectSoft Microservice Template, Application Insights is integrated as a first-class observability solution, automatically collecting telemetry data including requests, dependencies, exceptions, performance counters, and custom metrics.

Application Insights provides:

  • Automatic Instrumentation: Automatic collection of HTTP requests, dependencies, exceptions, and performance metrics
  • Distributed Tracing: End-to-end request tracing across microservices and dependencies
  • Performance Monitoring: Real-time performance metrics, response times, and throughput
  • Failure Analysis: Exception tracking, error rates, and failure diagnostics
  • Live Metrics Stream: Real-time metrics visualization with sub-second latency
  • Custom Telemetry: Application-specific events, metrics, and traces
  • Integration: Seamless integration with Serilog, health checks, and Microsoft Bot Framework

Application Insights Philosophy

Application Insights is the primary observability solution for Azure-hosted microservices. It provides automatic instrumentation, rich telemetry collection, and powerful analytics capabilities, enabling teams to monitor application health, diagnose issues, and optimize performance without manual instrumentation overhead.

Architecture Overview

Application Insights Integration

Application Insights is integrated at multiple layers of the microservice:

Application Code
├── Automatic Instrumentation
│   ├── HTTP Requests
│   ├── Dependencies (HTTP, SQL, Service Bus)
│   ├── Exceptions
│   └── Performance Counters
├── Custom Telemetry
│   ├── TelemetryClient
│   ├── Custom Events
│   ├── Custom Metrics
│   └── Custom Traces
├── Serilog Integration
│   └── Serilog.Sinks.ApplicationInsights
├── Health Checks Integration
│   └── ApplicationInsightsPublisher
└── Bot Framework Integration
    └── BotTelemetryClient
Azure Application Insights
├── Telemetry Ingestion
├── Analytics & Querying
├── Dashboards & Workbooks
└── Alerts & Notifications

Key Integration Points

Layer Component Purpose
Application TelemetryClient Custom telemetry tracking
Serilog Serilog.Sinks.ApplicationInsights Log forwarding to Application Insights
Health Checks ApplicationInsightsPublisher Health check results publishing
Bot Framework BotTelemetryClient Bot conversation telemetry
Automatic ASP.NET Core Integration Automatic request/dependency tracking

Configuration

Service Registration

Application Insights is registered via AzureApplicationInsightsExtensions:

// AzureApplicationInsightsExtensions.cs
internal static IServiceCollection AddMicroserviceAzureApplicationInsights(
    this IServiceCollection services)
{
    ArgumentNullException.ThrowIfNull(services);

    services.AddApplicationInsightsTelemetry(options =>
    {
        options.ConnectionString = OptionsExtensions.ApplicationInsightsServiceOptions.ConnectionString;
        options.DeveloperMode = OptionsExtensions.ApplicationInsightsServiceOptions.DeveloperMode;
        options.EnableAdaptiveSampling = OptionsExtensions.ApplicationInsightsServiceOptions.EnableAdaptiveSampling;
        options.EnableQuickPulseMetricStream = OptionsExtensions.ApplicationInsightsServiceOptions.EnableQuickPulseMetricStream;
        options.EnablePerformanceCounterCollectionModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnablePerformanceCounterCollectionModule;
        options.EnableDependencyTrackingTelemetryModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableDependencyTrackingTelemetryModule;
        options.EnableHeartbeat = OptionsExtensions.ApplicationInsightsServiceOptions.EnableHeartbeat;
        options.EnableEventCounterCollectionModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableEventCounterCollectionModule;
        options.EnableAppServicesHeartbeatTelemetryModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableAppServicesHeartbeatTelemetryModule;
        options.EnableAdaptiveSampling = OptionsExtensions.ApplicationInsightsServiceOptions.EnableAdaptiveSampling;
        options.EnableDebugLogger = OptionsExtensions.ApplicationInsightsServiceOptions.EnableDebugLogger;
        options.EnableDiagnosticsTelemetryModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableDiagnosticsTelemetryModule;
        options.EnableAzureInstanceMetadataTelemetryModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableAzureInstanceMetadataTelemetryModule;
        options.AddAutoCollectedMetricExtractor = OptionsExtensions.ApplicationInsightsServiceOptions.AddAutoCollectedMetricExtractor;
        options.EnableRequestTrackingTelemetryModule = OptionsExtensions.ApplicationInsightsServiceOptions.EnableRequestTrackingTelemetryModule;
    });

    // Register TelemetryClient for custom telemetry
    services.AddSingleton<TelemetryClient>();

    // Add correlation telemetry initializer
    services.AddSingleton<ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();

#if UseMicrosoftBotBuilder
    // Bot Framework telemetry integration
    services.AddSingleton<IBotTelemetryClient, BotTelemetryClient>();
    services.ActivateSingleton<IBotTelemetryClient>();
    services.AddSingleton<ITelemetryInitializer, TelemetryBotIdInitializer>();
    services.AddSingleton<TelemetryInitializerMiddleware>();
    services.AddSingleton<TelemetryLoggerMiddleware>();
#endif

    return services;
}

Configuration Options

Application Insights is configured via appsettings.json:

{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=...;IngestionEndpoint=https://...;LiveEndpoint=https://...",
    "DeveloperMode": true,
    "EnableQuickPulseMetricStream": true,
    "EnablePerformanceCounterCollectionModule": true,
    "EnableAppServicesHeartbeatTelemetryModule": true,
    "EnableAzureInstanceMetadataTelemetryModule": true,
    "EnableDependencyTrackingTelemetryModule": true,
    "EnableEventCounterCollectionModule": true,
    "EnableAdaptiveSampling": true,
    "EnableHeartbeat": true,
    "AddAutoCollectedMetricExtractor": true,
    "EnableRequestTrackingTelemetryModule": true,
    "EnableDiagnosticsTelemetryModule": true
  }
}

Configuration Options:

Option Type Default Description
ConnectionString string Required Application Insights connection string
DeveloperMode bool false Faster telemetry transmission in development
EnableQuickPulseMetricStream bool true Enable Live Metrics Stream
EnablePerformanceCounterCollectionModule bool true Collect Windows performance counters
EnableAppServicesHeartbeatTelemetryModule bool true Collect Azure App Service heartbeats
EnableAzureInstanceMetadataTelemetryModule bool true Collect Azure instance metadata
EnableDependencyTrackingTelemetryModule bool true Track HTTP, SQL, and other dependencies
EnableEventCounterCollectionModule bool true Collect .NET EventCounters
EnableAdaptiveSampling bool true Enable adaptive sampling to reduce data volume
EnableHeartbeat bool true Enable heartbeat telemetry
AddAutoCollectedMetricExtractor bool true Extract metrics from traces
EnableRequestTrackingTelemetryModule bool true Track HTTP requests automatically
EnableDiagnosticsTelemetryModule bool true Collect diagnostic telemetry

Connection String

The connection string format:

InstrumentationKey={GUID};IngestionEndpoint=https://{region}.in.applicationinsights.azure.com/;LiveEndpoint=https://{region}.livediagnostics.monitor.azure.com/

Components: - InstrumentationKey: Unique identifier for the Application Insights resource - IngestionEndpoint: Endpoint for telemetry ingestion (region-specific) - LiveEndpoint: Endpoint for Live Metrics Stream (region-specific)

Obtaining Connection String:

  1. Azure Portal → Application Insights resource
  2. Overview → Connection String
  3. Copy connection string to configuration

Automatic Telemetry Collection

HTTP Request Tracking

Application Insights automatically tracks HTTP requests:

  • Request URL: Full request path and query string
  • HTTP Method: GET, POST, PUT, DELETE, etc.
  • Response Status Code: HTTP status codes
  • Response Time: Request duration in milliseconds
  • Client IP: Client IP address (if available)
  • User Agent: Client user agent string
  • Correlation IDs: Distributed tracing correlation

Example Request Telemetry:

{
  "name": "GET /api/aggregates",
  "id": "|abc123.def456.",
  "duration": "00:00:00.123",
  "success": true,
  "responseCode": "200",
  "url": "https://api.example.com/api/aggregates",
  "properties": {
    "HttpMethod": "GET",
    "UserAgent": "Mozilla/5.0...",
    "ClientIp": "192.168.1.1"
  }
}

Dependency Tracking

Application Insights automatically tracks dependencies:

  • HTTP Calls: Outgoing HTTP requests to external services
  • Database Calls: SQL queries, connection strings (sanitized)
  • Service Bus: Message sends and receives
  • Azure Storage: Blob, Table, Queue operations
  • External APIs: Third-party service calls

Example Dependency Telemetry:

{
  "name": "GET https://api.example.com/users",
  "id": "|abc123.ghi789.",
  "duration": "00:00:00.456",
  "success": true,
  "type": "Http",
  "target": "api.example.com",
  "data": "GET /users",
  "properties": {
    "HttpStatusCode": "200"
  }
}

Exception Tracking

Application Insights automatically tracks exceptions:

  • Exception Type: Full exception type name
  • Exception Message: Exception message
  • Stack Trace: Full stack trace
  • Request Context: Associated request information
  • Custom Properties: Additional exception context

Example Exception Telemetry:

{
  "name": "System.ArgumentException",
  "message": "Value cannot be null. (Parameter 'id')",
  "problemId": "ArgumentException at MyService.Create",
  "severityLevel": "Error",
  "properties": {
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "at MyService.Create(String id) ...",
    "RequestId": "|abc123.def456."
  }
}

Performance Counters

Application Insights collects performance counters (Windows only):

  • CPU Usage: Processor utilization percentage
  • Memory Usage: Available memory, working set
  • Disk I/O: Disk read/write operations
  • Network I/O: Network bytes sent/received
  • .NET Counters: GC collections, thread pool, exceptions

Note: Performance counters are Windows-specific. On Linux, use EventCounters instead.

EventCounters

Application Insights collects .NET EventCounters (cross-platform):

  • CPU Usage: Processor time
  • Working Set: Memory usage
  • GC Counters: Garbage collection statistics
  • Thread Pool: Thread pool utilization
  • Exception Count: Exception rate

Custom Telemetry

TelemetryClient

Use TelemetryClient for custom telemetry tracking:

public class AggregateService
{
    private readonly TelemetryClient _telemetryClient;

    public AggregateService(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    public async Task<Aggregate> CreateAggregateAsync(CreateInput input)
    {
        using var operation = _telemetryClient.StartOperation<DependencyTelemetry>("CreateAggregate");
        operation.Telemetry.Type = "CustomOperation";
        operation.Telemetry.Data = $"Creating aggregate: {input.Name}";

        try
        {
            // Business logic
            var aggregate = await ProcessCreateAsync(input);

            // Track custom event
            _telemetryClient.TrackEvent("AggregateCreated", new Dictionary<string, string>
            {
                ["AggregateId"] = aggregate.Id.ToString(),
                ["AggregateName"] = aggregate.Name
            });

            // Track custom metric
            _telemetryClient.TrackMetric("AggregatesCreated", 1, new Dictionary<string, string>
            {
                ["Environment"] = "Production"
            });

            return aggregate;
        }
        catch (Exception ex)
        {
            _telemetryClient.TrackException(ex, new Dictionary<string, string>
            {
                ["Operation"] = "CreateAggregate",
                ["InputName"] = input.Name
            });
            throw;
        }
    }
}

Custom Events

Track custom business events:

_telemetryClient.TrackEvent("OrderPlaced", new Dictionary<string, string>
{
    ["OrderId"] = order.Id.ToString(),
    ["CustomerId"] = order.CustomerId.ToString(),
    ["TotalAmount"] = order.TotalAmount.ToString("C"),
    ["PaymentMethod"] = order.PaymentMethod
}, new Dictionary<string, double>
{
    ["OrderTotal"] = order.TotalAmount
});

Custom Metrics

Track custom metrics:

// Track metric with value
_telemetryClient.TrackMetric("OrdersPerMinute", 15.5, new Dictionary<string, string>
{
    ["Region"] = "West US"
});

// Track metric with aggregation
_telemetryClient.TrackMetric("ProcessingTime", processingTimeMs, new Dictionary<string, string>
{
    ["Operation"] = "ProcessOrder"
});

Custom Traces

Track custom trace messages:

_telemetryClient.TrackTrace("Processing order batch", SeverityLevel.Information, new Dictionary<string, string>
{
    ["BatchSize"] = batchSize.ToString(),
    ["BatchId"] = batchId.ToString()
});

Custom Dependencies

Track custom dependencies:

var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();

try
{
    // External service call
    await externalService.CallAsync();

    timer.Stop();
    _telemetryClient.TrackDependency("ExternalService", "CallAsync", startTime, timer.Elapsed, true);
}
catch (Exception ex)
{
    timer.Stop();
    _telemetryClient.TrackDependency("ExternalService", "CallAsync", startTime, timer.Elapsed, false);
    throw;
}

Serilog Integration

Serilog Sink Configuration

Serilog can forward logs to Application Insights:

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "InstrumentationKey=...;IngestionEndpoint=https://...",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ]
  }
}

Telemetry Converters

Application Insights Serilog sink supports multiple telemetry converters:

Converter Telemetry Type Use Case
TraceTelemetryConverter Traces Log messages as trace telemetry
EventTelemetryConverter Events Log messages as event telemetry
RequestTelemetryConverter Requests Log messages as request telemetry (requires HTTP context)

Example Configuration:

{
  "Args": {
    "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
  }
}

Benefits: - Unified Logging: All Serilog logs appear in Application Insights - Structured Data: Log properties are preserved as custom properties - Correlation: Logs are correlated with requests and dependencies - Search: Search logs alongside telemetry in Application Insights

Health Checks Integration

Health Checks Publisher

Application Insights can publish health check results:

// HealthChecksExtensions.cs
#if UseApplicationInsightsAsHealthChecksPublisher
builder.AddApplicationInsightsPublisher(
    connectionString: healthChecksOptions.ApplicationInsightsPublisher.ConnectionString,
    saveDetailedReport: healthChecksOptions.ApplicationInsightsPublisher.SaveDetailedReport,
    excludeHealthyReports: healthChecksOptions.ApplicationInsightsPublisher.ExcludeHealthyReports);
#endif

Configuration

{
  "HealthChecks": {
    "ApplicationInsightsPublisher": {
      "ConnectionString": "InstrumentationKey=...;IngestionEndpoint=https://...",
      "SaveDetailedReport": false,
      "ExcludeHealthyReports": false
    }
  }
}

Configuration Options:

Option Type Description
ConnectionString string Application Insights connection string
SaveDetailedReport bool Save detailed report for each health check (vs. global status)
ExcludeHealthyReports bool Only save unhealthy health check reports

Benefits: - Health Monitoring: Track health check results over time - Alerting: Create alerts based on health check failures - Trending: Analyze health check trends and patterns - Correlation: Correlate health check failures with application issues

Microsoft Bot Framework Integration

Bot Telemetry

Application Insights integrates with Microsoft Bot Framework:

// AzureApplicationInsightsExtensions.cs
#if UseMicrosoftBotBuilder
// Create the telemetry client
services.AddSingleton<IBotTelemetryClient, BotTelemetryClient>();
services.ActivateSingleton<IBotTelemetryClient>();

// Add telemetry initializer for bot-specific properties
services.AddSingleton<ITelemetryInitializer, TelemetryBotIdInitializer>();

// Create telemetry middleware
services.AddSingleton<TelemetryInitializerMiddleware>();
services.AddSingleton<TelemetryLoggerMiddleware>();
#endif

Bot Telemetry Features: - Conversation Tracking: Track bot conversations and user interactions - Intent Recognition: Track LUIS/QnA Maker intents and entities - Dialog Flow: Track dialog state transitions - Custom Events: Track custom bot events (e.g., "UserLoggedIn", "OrderPlaced")

Example Bot Telemetry:

public class MyBot : ActivityHandler
{
    private readonly IBotTelemetryClient _telemetryClient;

    public MyBot(IBotTelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    protected override async Task OnMessageActivityAsync(
        ITurnContext<IMessageActivity> turnContext, 
        CancellationToken cancellationToken)
    {
        // Track message received
        _telemetryClient.TrackEvent("MessageReceived", new Dictionary<string, string>
        {
            ["UserId"] = turnContext.Activity.From.Id,
            ["Channel"] = turnContext.Activity.ChannelId,
            ["Message"] = turnContext.Activity.Text
        });

        // Bot logic
        await turnContext.SendActivityAsync("Hello!");
    }
}

Telemetry Initializers

Operation Correlation Telemetry Initializer

Automatic correlation context initialization:

services.AddSingleton<ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();

Purpose: Ensures all telemetry items are correlated with the current operation context.

Custom Telemetry Initializers

Create custom telemetry initializers to enrich telemetry:

public class EnvironmentTelemetryInitializer : ITelemetryInitializer
{
    private readonly IWebHostEnvironment _environment;

    public EnvironmentTelemetryInitializer(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    public void Initialize(ITelemetry telemetry)
    {
        telemetry.Context.Cloud.RoleName = _environment.ApplicationName;
        telemetry.Context.Cloud.RoleInstance = Environment.MachineName;
        telemetry.Context.GlobalProperties["Environment"] = _environment.EnvironmentName;
        telemetry.Context.GlobalProperties["Version"] = Assembly.GetExecutingAssembly().GetName().Version?.ToString();
    }
}

Registration:

services.AddSingleton<ITelemetryInitializer, EnvironmentTelemetryInitializer>();

Sampling

Adaptive Sampling

Adaptive sampling reduces telemetry volume while preserving representative data:

{
  "ApplicationInsights": {
    "EnableAdaptiveSampling": true
  }
}

How It Works: - Automatic Adjustment: Sampling rate adjusts based on telemetry volume - Preserve Important Events: Exceptions and important events are always sent - Maintain Representative Data: Sample preserves statistical representativeness

Custom Sampling

Configure custom sampling policies:

services.AddApplicationInsightsTelemetry(options =>
{
    options.EnableAdaptiveSampling = false;
});

services.AddSingleton<ITelemetryProcessorFactory>(sp =>
{
    return new TelemetryProcessorFactory();
});

public class TelemetryProcessorFactory : ITelemetryProcessorFactory
{
    public ITelemetryProcessor Create(ITelemetryProcessor next)
    {
        return new SamplingTelemetryProcessor(next)
        {
            SamplingPercentage = 10.0 // Sample 10% of telemetry
        };
    }
}

Live Metrics Stream

Live Metrics Stream provides real-time metrics with sub-second latency:

{
  "ApplicationInsights": {
    "EnableQuickPulseMetricStream": true
  }
}

Features: - Real-Time Metrics: Metrics updated in real-time (sub-second latency) - Server Metrics: CPU, memory, request rate, failed requests - Dependency Metrics: Dependency call rates and failures - Exception Tracking: Exceptions as they occur - Custom Metrics: Application-specific metrics

Access: Azure Portal → Application Insights → Live Metrics

Querying Telemetry

Application Insights Analytics

Query telemetry using Kusto Query Language (KQL):

// Requests in the last hour
requests
| where timestamp > ago(1h)
| summarize count() by bin(timestamp, 5m), resultCode
| render timechart

// Dependencies with failures
dependencies
| where success == false
| where timestamp > ago(1h)
| project timestamp, name, type, data, resultCode
| order by timestamp desc

// Exceptions grouped by type
exceptions
| where timestamp > ago(24h)
| summarize count() by type
| order by count_ desc

// Custom events
customEvents
| where name == "OrderPlaced"
| where timestamp > ago(1h)
| project timestamp, customDimensions

Log Analytics Workspace

Application Insights data can be queried in Log Analytics:

// Query Application Insights tables
AppRequests
| where TimeGenerated > ago(1h)
| summarize count() by bin(TimeGenerated, 5m), ResultCode

AppDependencies
| where TimeGenerated > ago(1h)
| where Success == false
| project TimeGenerated, Name, Type, Data

AppExceptions
| where TimeGenerated > ago(24h)
| summarize count() by ExceptionType
| order by count_ desc

Dashboards and Workbooks

Application Insights Dashboards

Create dashboards to visualize key metrics:

  1. Azure Portal → Application Insights → Dashboards
  2. Add tiles for:
  3. Request rate
  4. Response time
  5. Failure rate
  6. Dependency calls
  7. Exceptions
  8. Custom metrics

Workbooks

Create interactive workbooks for detailed analysis:

  1. Azure Portal → Application Insights → Workbooks
  2. Create custom workbooks with:
  3. Metrics charts
  4. Log queries
  5. Parameters
  6. Links

Alerts

Metric Alerts

Create alerts based on metrics:

  1. Azure Portal → Application Insights → Alerts
  2. Create alert rule:
  3. Signal Type: Metric
  4. Metric: Request rate, response time, failure rate, etc.
  5. Condition: Threshold, aggregation
  6. Action Group: Email, SMS, webhook, etc.

Log Alerts

Create alerts based on log queries:

// Alert on high error rate
requests
| where timestamp > ago(5m)
| summarize errorCount = countif(success == false), totalCount = count()
| extend errorRate = errorCount * 100.0 / totalCount
| where errorRate > 5.0

Best Practices

Do's

  1. Use Connection String

    // ✅ GOOD - Use connection string (recommended)
    {
      "ConnectionString": "InstrumentationKey=...;IngestionEndpoint=..."
    }
    

  2. Enable Adaptive Sampling in Production

    // ✅ GOOD - Enable adaptive sampling
    {
      "EnableAdaptiveSampling": true
    }
    

  3. Track Custom Business Events

    // ✅ GOOD - Track business events
    _telemetryClient.TrackEvent("OrderPlaced", properties);
    

  4. Use Correlation IDs

    // ✅ GOOD - Include correlation context
    telemetry.Context.Operation.Id = correlationId;
    

  5. Enrich Telemetry with Context

    // ✅ GOOD - Add business context
    telemetry.Properties["TenantId"] = tenantId;
    telemetry.Properties["UserId"] = userId;
    

Don'ts

  1. Don't Log Sensitive Data

    // ❌ BAD - Logging sensitive data
    _telemetryClient.TrackEvent("UserLogin", new Dictionary<string, string>
    {
        ["Password"] = password  // Never!
    });
    
    // ✅ GOOD - Exclude sensitive data
    _telemetryClient.TrackEvent("UserLogin", new Dictionary<string, string>
    {
        ["UserId"] = userId
    });
    

  2. Don't Disable Sampling in Production

    // ❌ BAD - Disable sampling (high cost)
    {
      "EnableAdaptiveSampling": false
    }
    
    // ✅ GOOD - Enable adaptive sampling
    {
      "EnableAdaptiveSampling": true
    }
    

  3. Don't Track Excessive Custom Metrics

    // ❌ BAD - Too many custom metrics
    for (int i = 0; i < 1000; i++)
    {
        _telemetryClient.TrackMetric($"Metric{i}", value);
    }
    

  4. Don't Ignore Performance Impact

    // ❌ BAD - Synchronous telemetry in hot path
    _telemetryClient.TrackEvent("Operation", properties); // Blocks
    
    // ✅ GOOD - Use async or fire-and-forget
    _ = Task.Run(() => _telemetryClient.TrackEvent("Operation", properties));
    

Troubleshooting

Issue: No Telemetry Appearing

Symptom: Telemetry not appearing in Application Insights.

Solutions: 1. Verify connection string is correct 2. Check network connectivity to ingestion endpoint 3. Verify EnableRequestTrackingTelemetryModule is true 4. Check Application Insights resource is active 5. Review Application Insights logs for errors

Issue: High Telemetry Volume

Symptom: High costs due to telemetry volume.

Solutions: 1. Enable adaptive sampling: "EnableAdaptiveSampling": true 2. Configure custom sampling policies 3. Reduce custom telemetry tracking 4. Use sampling filters for verbose telemetry

Issue: Missing Dependencies

Symptom: Dependencies not tracked automatically.

Solutions: 1. Verify EnableDependencyTrackingTelemetryModule is true 2. Check dependency is supported (HTTP, SQL, Service Bus, etc.) 3. Use TelemetryClient.TrackDependency for custom dependencies 4. Verify dependency tracking is enabled for the framework

Issue: Correlation Not Working

Symptom: Telemetry items not correlated across services.

Solutions: 1. Verify OperationCorrelationTelemetryInitializer is registered 2. Check HTTP header propagation is configured 3. Verify correlation headers are passed between services 4. Use distributed tracing (OpenTelemetry) for multi-service correlation

Summary

Azure Application Insights in the ConnectSoft Microservice Template provides:

  • Automatic Instrumentation: Automatic collection of requests, dependencies, exceptions
  • Custom Telemetry: Track custom events, metrics, and traces
  • Serilog Integration: Forward Serilog logs to Application Insights
  • Health Checks Integration: Publish health check results
  • Bot Framework Integration: Track bot conversations and interactions
  • Live Metrics Stream: Real-time metrics with sub-second latency
  • Sampling: Adaptive sampling to reduce costs
  • Querying: KQL queries for telemetry analysis
  • Dashboards: Visualize key metrics and trends
  • Alerts: Automated alerts based on metrics and logs

By following these patterns, teams can:

  • Monitor Application Health: Track performance, availability, and errors
  • Diagnose Issues: Analyze failures, exceptions, and performance problems
  • Optimize Performance: Identify bottlenecks and optimize slow operations
  • Understand User Behavior: Track user interactions and business events
  • Reduce Costs: Use sampling and filtering to manage telemetry volume
  • Improve Reliability: Proactive monitoring and alerting for issues

Application Insights is a comprehensive observability solution that provides deep insights into application behavior, enabling teams to build, deploy, and operate reliable, high-performance microservices.