Home > OS >  How to log to app insights from .NET Core 6
How to log to app insights from .NET Core 6

Time:11-15

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. In the Azure portal, I see 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?

What other info can I provide in order to help with the clarity of this question?

CodePudding user response:

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()});
    // ...
} 
  • Related