How to use Azure Application Insights in ASP.NET Core

Take advantage of Application Insights to monitor performance and detect and diagnose performance issues in your web application

How to use Azure Application Insights in ASP.NET Core
Thinkstock

Azure Application Insights is an extensible application performance management (APM) service that can be used to monitor performance, detect anomalies, and diagnose performance issues for a web application in real time. If you are using .NET Core, you can use Application Insights on the multiple platforms that .NET Core supports (Windows, Linux, or Mac).

Note that you can use Application Insights for applications built in various technologies including .NET, JavaScript, Node.js, and Java as well as .NET Core. And you can use Application Insights for such applications whether or not they are hosted in the cloud. In this article we’ll examine how you can log data to Azure Application Insights in an ASP.NET Core application.

To work with the code examples illustrated in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

You will also need an Azure account as we’ll be pushing the log messages to Application Insights in Azure. If you don’t have an Azure account, you can create a free Azure account here. In the sections that follow, we’ll examine how we can configure Application Insights as one of the sinks for the default logger in ASP.NET Core.

Create an ASP.NET Core API project

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.NET Core Web Application” window, select .NET Core as the runtime and choose ASP.NET Core 2.2 (or later) from the drop-down list at the top.
  8. Select “API” as the project template to create a new ASP.NET Core API application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  11. Click Create.

This will create a new ASP.NET Core API project in Visual Studio. We’ll use this project in the subsequent sections of this article.

Install the NuGet packages for Application Insights

Now that we have created an ASP.NET Core API project in Visual Studio, the next thing you should do is install the necessary NuGet packages. To do this, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages...”. Then install the following packages from the NuGet Package Manager:

  • Microsoft.ApplicationInsights.AspNetCore
  • Microsoft.Extensions.Logging.ApplicationInsights

Alternatively, you can install these packages from the NuGet Package Manager Console by entering the following commands:

Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package  Microsoft.Extensions.Logging.ApplicationInsights

In the next section, we’ll set up our application’s connection to Application Insights. You will need an Azure account to proceed to the next step.

Configure logging to Application Insights in AppSettings.json

We will need an instrumentation key to connect to Application Insight in Azure and log data. We’ll specify this in the AppSettings.json file. Here is what the contents of the AppSettings.json file will look like:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    },
    "ApplicationInsights": {
      "InstrumentationKey": "Write your instrumentation key here"
    }
  },
  "AllowedHosts": "*"
}

Configure logging to Application Insights in the Program class

The next step is to configure logging in the Program class in the Program.cs file. The following code snippet shows how this can be achieved.

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilderForApplicationInsights(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilderForApplicationInsights(string[] args)
        {
            var webHostBuilder = WebHost.CreateDefaultBuilder(args);
            webHostBuilder.UseStartup<Startup>()
                .ConfigureLogging((hostingContext, loggingBuilder) =>
                {
                    var loggingConfiguration = hostingContext.Configuration.GetSection("Logging");
                    if (!string.IsNullOrWhiteSpace(
                        loggingConfiguration["ApplicationInsights:InstrumentationKey"]))
                    {
                        var logLevel = loggingConfiguration["LogLevel:Default"];
                        loggingBuilder.AddApplicationInsights(loggingConfiguration
                            ["ApplicationInsights:InstrumentationKey"]?.ToString() ?? "");
                        loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>
                        ("", Enum.Parse<LogLevel>(logLevel ?? "Information"));
                        loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>
                        ("Default", Enum.Parse<LogLevel>(logLevel ?? "Warning"));
                    }
                });
            return webHostBuilder;
        }
    }

Configure logging to Application Insights in the Startup class

Write the following code in the ConfigureServices method to add ApplicationInsightsTelemetry to the request processing pipeline.

var instrumentationKey = Configuration.GetValue<string>
         ("ApplicationInsights:InstrumentationKey");
services.AddApplicationInsightsTelemetry(instrumentationKey);

Create logs in the controller method in .NET Core

The following code listing shows how you can log data from the controller.

 public class ValuesController : ControllerBase
  {
        private readonly ILogger _logger;
        public ValuesController(ILogger<ValuesController> logger)
        {
           _logger = logger;
        }
      [HttpGet]
        public ActionResult<string> Get()
        {
           _logger.LogInformation("This is a test for checking the logger"
            + DateTime.Now.ToLongTimeString());
            return "Hello World";
        }
   }

Application Insights can monitor request rates, response times, exceptions, failure rates, and even custom metrics you write in your application’s code. Further, Application Insights supports applications in a variety of languages on several platforms, and it works with several logging frameworks. In a future post here, we’ll examine how we can use a sink for Serilog that is capable of writing log data to Application Insights.

Copyright © 2019 IDG Communications, Inc.