13
votes

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 logging of informational messages into App Insight, ex. _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, log entries such as exceptions), however none of our calls to logger.LogInformation("Info here") are being send/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.

https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#control-logging-level

Where are we going wrong?

1

1 Answers

18
votes

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.