ILogger<TCategory> with Azure App Service Application Insights + Live Metrics

Goal

Send ILogger<TCategory> logs to Azure Application Insights and enable Live Metrics.

Setup Application Insights

Install the package:

dotnet add package Microsoft.ApplicationInsights.AspnetCore

Register the service:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    ...
}

Configure the instrumentation key:

// appsettings.json
{
    "ApplicationInsights": {
        "InstrumentationKey": "putinstrumentationkeyhere"
    },
    ...
}

Alternatively, pass the key directly to AddApplicationInsightsTelemetry().

Configure ILogger to Send to Application Insights

// Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
            logging.AddApplicationInsights()
                .AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information); 
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

The Console provider is useful for local debugging. Log level for Application Insights is explicitly set to Information.

Note: You can also use TelemetryClient directly for custom telemetry.

View Logs

Logs appear in the traces collection in Application Insights, not in requests.

Enable Live Metrics

dotnet add package Microsoft.ApplicationInsights.PerfCounterCollector

No additional configuration needed.