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?
Open Visual Studio. Select File | New Project. Select Visual C# | . NET Core | ASP.NET Core Web Application, ensure to mark the checkbox Add Application Insights to Project.
Add Application Insights automatically From within your ASP.NET web app project in Visual Studio: Select Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close.
Logging configuration is commonly provided by the Logging section of appsettings.{ENVIRONMENT}.json files, where the {ENVIRONMENT} placeholder is the environment. The following appsettings.Development.json file is generated by the ASP.NET Core web app templates: JSON Copy.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With