Joydip Kanjilal
Contributor

How to use Azure Application Insights in ASP.NET Core

how-to
Sep 30, 20195 mins
C#Cloud ComputingMicrosoft .NET

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

abstract data analytics
Credit: 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author