Search code examples
c#azure-functions.net-6.0azure-application-insights

How to log to App Insights from .NET Core 6?


I have a solution with 2 projects:

  1. Function app project
  2. ASP.NET Core 6.0 Web API project

The function app is successfully logging to App Insights, but the Web API project is not! Azure portal is showing that both of the projects are configured to write to the same instance of app insights.

Is it a problem that two different resources are writing to the same App Insights instance? If not, what am I doing wrong?


Solution

  • To configure Application Insights with telemetry you need to configure both telemetry and logging independently. Manual configuration or convention based in config configuration can both be used:

    https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core?tabs=netcore6

    Manually setting options when configuring DI:

    public void ConfigureServices(IServiceCollection service)
    {
        // ...
        ApplicationInsightsServiceOptions telemetryOptions = new ();
    telemetryOptions.InstrumentationKey = YourInstrumentationKey;
    
        // Can enable/disable adaptive sampling here.
        // https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling
        telemetryOptions.EnableAdaptiveSampling = false;
        services.AddApplicationInsightsTelemetry(telemetryOptions);
    
        services.AddLogging(logBuilder =>
                 {
                     logBuilder.AddApplicationInsights(YourInstrumentationKey)
                         // adding custom filter for specific use case. 
                         .AddFilter("Orleans", (level) => level == LogLevel.Error);
        });
        // ...
    } 
    

    When using appsettings.json:

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

    Then DI is can be slightly simplified:

    public void ConfigureServices(IServiceCollection service)
    {
        // ...
        services.AddApplicationInsightsTelemetry();
        services.AddLogging(logBuilder => logBuilder.AddApplicationInsights());
        // ...
    }