ILogger<TCategory> with azure app service Application Insights, plus Live Metrics

Add Application Insights to the webapi

Add the package

dotnet add package Microsoft.ApplicationInsights.AspnetCore

Register the service

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

Set the instrumentation key in the appsettings.json.

It can also be provided to AddApplicationInsightsTelemetry method when registering the service.

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

Add the ApplicationInsights logging provider

This is for the ILogger injected object to send to ApplicationInsights as well. I also like to add Console provider, so I can see what’s going on in the Console when running locally. The ApplicationInsights procider log level is set explicitely here in code.

// 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>();
        });

Also TelemetryClient can be explicitely used for ApplicationInsights.

Checking log messages

The messages are sent to the traces collection in Application Insights. Not the requests, but the traces collection.

Adding Application Insights Live Metrics

In case Live Metrics is desired, just add the following nuget to the project and that’s it

dotnet add package Microsoft.ApplicationInsights.PerfCounterCollector