Search This Blog

2021-03-03

Integrate Application Insight With .NET Core WebAPI

Configure Azure Web App Configuration

Add the below configuration key in the configuration of azure web app

{

    "name": "Logging.ApplicationInsights.LogLevel.Default",

    "value": "Information",

    "slotSetting": false

  },

  {

    "name": "Logging.ApplicationInsights.LogLevel.APP1.Service",

    "value": "Debug",

    "slotSetting": false

  },

  {

    "name": "Logging.ApplicationInsights.LogLevel.Microsoft",

    "value": "Error",

    "slotSetting": false

  },

  {

    "name": "LogLevel.Default",

    "value": "Information",

    "slotSetting": false

  },

  {

    "name": "LogLevel.Microsoft",

    "value": "Warning",

    "slotSetting": false

  },

  {

    "name": "LogLevel.Microsoft.Hosting.Lifetime",

    "value": "Information",

    "slotSetting": false

  }

Add Instrumentation Key in AppSetting.json

In application.development.json or Appsetting.loal.json add the APPINSIGHTS_INSTRUMENTATIONKEY key from Azure App Insight

"APPINSIGHTS_INSTRUMENTATIONKEY": "9d6e43e7-123c-4bfa-b80e-67c699998a4f"

Add the same key in the web app configuration


The key can be found from Application insight in azure



Install Nuget Package and Configure Applicaton 


Install the nuget package - Microsoft.Extensions.Logging

In Program.cs as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace App1.Service
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>()
                .ConfigureLogging(
                builder =>
                {
                    builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                        ("", LogLevel.Trace);
                }
            );

          });
    }
}

Configure Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddLocalization();
// The following line enables Application Insights telemetry collection.
services.AddApplicationInsightsTelemetry(options => {
                options.EnableDebugLogger = true;
                options.InstrumentationKey = this.Configuration.GetSection(FISResource.APP_KEY_APPINSIGHTS_INSTRUMENTATIONKEY).Get<string>();
            });
}

No comments: