top of page

Azure Application Insights in ASP.NET Core



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.


The Application Insights SDK for ASP.NET Core can monitor your applications no matter where or how they run. If your application is running and has network connectivity to Azure, telemetry can be collected. Application Insights monitoring is supported everywhere .NET Core is supported and covers the following scenarios:

  • Operating system: Windows, Linux, or Mac

  • Hosting method: In-process or out of the process

  • Deployment method: Framework dependent or self-contained

  • Web server: IIS (Internet Information Server) or Kestrel

  • Hosting platform: The Web Apps feature of Azure App Service, Azure VM, Docker, Azure Kubernetes Service (AKS), and so on

  • .NET Core version: All officially supported .NET Core versions that aren't in the preview

  • IDE: Visual Studio, Visual Studio Code, or command line


Enable Application Insights server-side telemetry (Visual Studio)

For Visual Studio for Mac, use the manual guidance. Only the Windows version of Visual Studio supports this procedure.

  1. Open your project in Visual Studio.

  2. Go to Project > Add Application Insights Telemetry.

  3. Choose Azure Application Insights, then select Next.

  4. Choose your subscription and Application Insights instance (or create a new instance with Create new), then select Next.

  5. Add or confirm your Application Insights connection string (this should be prepopulated based on your selection in the previous step), then select Finish.

  6. After you add Application Insights to your project, check to confirm that you're using the latest stable release of the SDK. Go to Project > Manage NuGet Packages... > Microsoft.ApplicationInsights.AspNetCore. If you need to, select Update.

Enable Application Insights server-side telemetry (no Visual Studio)

1. Install the Application Insights SDK NuGet package for ASP.NET Core We recommend that you always use the latest stable version. Find full release notes for the SDK on the open-source GitHub repo.

The following code sample shows the changes to be added to your project's .csproj file.

<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
</ItemGroup>

2. Add AddApplicationInsightsTelemetry() to your startup.cs or program.cs class (ASP.NET Core 6.0 version)


Add builder.Services.AddApplicationInsightsTelemetry(); after the WebApplication.CreateBuilder() method in your Program class, as in this example:

// This method gets called by the runtime. 
//Use this method to add services to the container.
var builder = WebApplication.CreateBuilder(args);  

// The following line enables Application Insights telemetry collection. 
builder.Services.AddApplicationInsightsTelemetry();  

// This code adds other services for your application. builder.Services.AddMvc();  

var app = builder.Build(); 

3. Set up the connection string Although you can provide a connection string as part of the ApplicationInsightsServiceOptions argument to AddApplicationInsightsTelemetry, we recommend that you specify the connection string in configuration. The following code sample shows how to specify a connection string in appsettings.json. Make sure appsettings.json is copied to the application root folder during publishing.

{   
    "Logging": 
    {     
        "LogLevel": 
        {       
            "Default": "Information",       
            "Microsoft.AspNetCore": "Warning"     
         }   
     },   
     "AllowedHosts": "*",   
     "ApplicationInsights": 
     {     
         "ConnectionString": "Copy connection string from Application 
         Insights Resource Overview"   
     } 
} 

Alternatively, specify the connection string in the "APPLICATIONINSIGHTS_CONNECTION_STRING" environment variable or "ApplicationInsights:ConnectionString" in the JSON configuration file.

For example:

  • SET ApplicationInsights:ConnectionString = <Copy connection string from Application Insights Resource Overview>

  • SET APPLICATIONINSIGHTS_CONNECTION_STRING = <Copy connection string from Application Insights Resource Overview>

  • Typically, APPLICATIONINSIGHTS_CONNECTION_STRING is used in Azure Web Apps, but it can also be used in all places where this SDK is supported.


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.



Resource: Microsoft, infoworld.com

The Tech Platform

1 comment
bottom of page