Search code examples
c#asp.net-core.net-coreappinsights

Why is the App Insight LogLevel in appsettings being ignored?


We use ILogger in an ASP.NET Core 3.1 website, using the Microsoft.ApplicationInsights.AspNetCore package, version 2.14. We are trying to enable the logging of informational messages into App Insight, e.g., _logger.LogInformation("info here").

In our startup in ConfigureServices, we enable App Insights:

services.AddApplicationInsightsTelemetry();

We have the following in our appsettings.json file:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ApplicationInsights": {
        "InstrumentationKey": "12345678-1234-5678-1234-1234567890ab",
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    }
}

It picks up the app insight key correctly (we do get the normal metrics, and log entries such as exceptions), however none of our calls to logger.LogInformation("Info here") are being sent/recorded in the App Insight dashboard.

I found this question which is similar:

ILogger Not Respecting Log Level for Application Insights

But the answer still doesn't really address how to be able to change the log level from the appsettings.json file vs. hard-coding the log level into the code.

It seems like, from the docs, this should "just work", but it doesn't appear to.

Application Insights logging with .NET

Where are we going wrong?


Solution

  • You've got the LogLevel property for ApplicationInsights in the wrong place. Here's what it should look like:

    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        },
        "ApplicationInsights": {
            "LogLevel": {
                "Default": "Information",
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Information"
            }
        }
    },
    "ApplicationInsights": {
        "InstrumentationKey": "12345678-1234-5678-1234-1234567890ab"    
    }
    

    The log-level configuration lives under the Logging parent, but the InstrumentationKey lives outside of that hierarchy.

    See Configure logging in the official ASP.NET Core docs for more about provider-specific configuration.

    Also How do I customize ILogger logs collection? in documentation about Application Insights for ASP.NET Core applications