How to add Application Insights into an ASP.NET Core Web and Console App

Dec 05, 2019

Application Insights is Microsoft Azure's monitoring offering for not just dotnet apps, but Node.js and Java as well. It can be easily integrated into web based and console based applications as well as mobile apps. Application insights can track and monitor live statistics and metrics such as http requests rates, response times, exceptions and more. Once integrated, there is a wealth of information in the Application Insights section within the Azure Portal. So much it can be a little overwhelming.

However, it can provide a wealth of information that is useful when diagnosing issues such as performance issues.

Additionally, any ILogger statements within your application code, can also be captured by Application Insights as well.

In the examples below, I will demonstrate how to add Azure's Application Insights in a dot net core web, api, and a console application.

Add Application Insights

If you haven't done so already, create a new Application Insights resource in Azure. Then make a note of the InstrumentationKey from the portal.

app-insights-instrumentation-key

Adding Application Insights to a .Net Core Web or API app

There are few methods of adding Application Insights, and we'll go through each one. There are no pros or cons of each. Just different ways of integrating depending on the application and when you need or if you need access to logging immediately from Startup.

NuGet packages are required:

Option 1 - Add within Program.cs

In no particular order, the first method of adding Application Insights is directly in Program.cs using the ConfigureLogging extension method, which is part of the Microsoft.AspNetCore.Hosting namespace.

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(builder => 
        { 
            builder.AddApplicationInsights("insert-insights-key-here");
            builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("",LogLevel.Information);
            builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Error);
        });
}

Option 2 - Add within Startup.cs

The alternative is to use the ConfigureServices method in Startup to configure and add Application Insights.

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(builder =>
    {
        builder.AddApplicationInsights("insert-insights-key-here");
        builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
        builder.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Error);
    });
}

Add Telemetry

To integrate telemetry into Application Insights, it's one additional line we need to add in the ConfigureServices method within Startup.cs.

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

That's it! Application Insights is integrated.

Adding Application Insights to a .Net Core Console App

Adding Application Insights to a console app is exactly the same as a web or API app as shown above. The only difference is how we integrate telemetry.

public void ConfigureServices(IServiceCollection services)
{
    // option 2: 
    services.AddLogging(builder =>
    {
        builder.AddApplicationInsights("insert-insights-key-here");
        builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
        builder.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Error);
    });

}

Adding Telemetry

Again, similar to integrating telemetry in a web app environment, it's an additional line, but this is specific for console apps.

The following NuGet package is required:

public void ConfigureServices(IServiceCollection services)
{
    ...
    
    services.AddApplicationInsightsTelemetryWorkerService();

    ...
}

Configuring Logging levels.

To configure logging levels, there are two methods, either declaratively in code, or within config.

Option 1: Declarative logging

As shown in the above sections, specifying the logging level can be achieved directly in code.

builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);

This will log everything from Information and above.

Option 2: Using appsettings config

You can also configure logging via config. The standard logging section can be added into appsettings.json if not added already by default.

Application Insights will recognise this and automatically inject the logging level defined from config.

{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information"
    }
  }
}

If this config is included, the statement builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information); is no longer required.

Verifying Application Insights is working

To verify your web or console app has indeed Application Insights integrated, it should be pretty obvious as we should start to see live telemetry in the Azure portal.

Viewing live telemetry

You can view live telemetry via the Azure Portal by clicking on the "Live Metrics Stream" in the menu and you should see something like this.

app-insights-live-metrics

Viewing trace or log statements

Whilst you can view log and trace statements in the Azure Portal, just note that it's not immediate and there is a slight delay. So you will have to be a little patient.

Verifying log statements is slightly hidden, you will need to click on "Search".

app-insights-search-button

Then, using the search feature and after a slight delay, you should see log statements.

app-insights-logs

Summary

As you can see it is relatively straight forward to integrate Application Insights into a web and console application without too much involvement.
You can find sample code in my GitHub repo.

References

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.