I have an application where I am trying to log messages to Application Insights. I am relatively new to Application Insights and the Microsoft logging framework so I may be getting some of the terminology wrong here but I'm happy to clarify if anything is unclear.
I have tried following the guide here: https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#aspnet-core-application i.e. simply calling the AddApplicationInsightsTelemetry method on the IServiceCollection in my Startup class and then injecting an ILogger in one of my controllers to try to log a message.
I have not tried configuring a filter to set a minimum severity level so I am simply doing _logger.LogWarning("My message") since warnings should be logged by default.
After hitting my controller I checked the traces in Application Insights but could not see my message there. I did however see telemetry data, e.g. I could see requests hitting my application being logged.
I then attached a debugger and stepped through the code in my controller and noticed that my ILogger did not contain an ApplicationInsightsLogger. I also tried to inject an ILoggerFactory and calling the CreateLogger method on it with the same result, i.e. the logger does not contain an ApplicationInsightsLogger.
This seems to indicate that for some reason an ApplicationInsightsLoggerProvider is not being registered by the call to AddApplicationInsightsTelemetry or that something is clearing the LoggerProviders after it has been added but I can not see anything in my Startup class that seems like it would do that.
I should mention that there is another project in the same solution, using the same version of Microsoft.ApplicationInsights.AspNetCore (2.14.0) where I do the same thing but there the log messages do show up in Application Insights.
Any idea at all what the issue here could be or how I could continue troubleshooting it?
Update
I've done some more digging into this and the problem definitely be that for some reason the call to AddApplicationInsightsTelemetry("myInstrumentationKey") is not registering an ILoggerProvider. I experimented with doing the following in Startup.ConfigureServices:
services.AddApplicationInsightsTelemetry("myInstrumentationKey");
var sp = services.BuildServiceProvider();
var loggerFactory = sp.GetService<ILoggerFactory>();
And when I attached the debugger and inspected the resolved loggerFactory the _providerRegistrations property is empty. In the other project in the same solution where I have gotten this to work this property contains an Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider. This seems to me to rule out the option that something later on in Startup is clearing the registered providers, it's simply not getting added in the first place.
Is there any reason that anyone knows why this call should fail to register an ApplicationInsightsLoggerProvider? Is there anyway I could find out why it fails to do so? I've tried checking the Windows Event log but can't see any errors or warnings related to this.
Update 2
I forgot about this question but here's another late update.
The project where I do not get an ApplicationInsightsLoggerProvider uses AspNetCore 1.1.1 and the project where I do get an ApplicationInsightsLoggerProvider is using AspNetCore 2.0.2. So my assumption for is that this is at least in part what is causing the issue. Both of them have net461 as their target framework.
In the end I managed to get around this issue by calling
loggerFactory.AddApplicationInsights(app.ApplicationServices);
in the Configure method in my Startup class.
I get an obsolete warning stating that I should be using the AddApplicationInsightsTelemetry extension method on IServiceCollection (which, as stated, doesn't work) or the UseApplicationInsights extension method on IWebHostBuilder which is also marked as obsolete in favor of AddApplicationInsightsTelemetry. It also claims that using the AddApplicationInsights method will result in double logging but that does not seem to happen in my case either so until we get around to updating this project to use a newer version of AspNetCore I think this will have to do.
If you want to log the error as Exception in app insights, this line of code _logger. LogError("Test", new Exception("Test")); should be changed. Change it to _logger. LogError(new Exception(), "test"); , which means the new Exception() should be the first paramter.
The instrumentation key identifies the resource that you want to associate your telemetry data with. You will need to copy the instrumentation key and add it to your application's code.
By adjusting the configuration file, you can enable or disable Telemetry Modules and initializers, and set parameters for some of them. The configuration file is named ApplicationInsights. config or ApplicationInsights. xml , depending on the type of your application.
ApplicationInsightsLoggerProvider is enabled by default for ASP.NET Core applications when ApplicationInsights is configured using Code or Code-less approach. Only Warning and above ILogger logs (from all categories) are sent to Application Insights by default. But you can customize this behavior.
To add Application Insights telemetry to ASP.NET Core applications, use the Microsoft.ApplicationInsights.AspNetCore NuGet package. This can be configured through Visual Studio as a Connected service, or manually.
Application Insights captures and sends ILogger logs by using the same TelemetryConfiguration information that's used for every other telemetry. But there's an exception.
If an Exception object is passed to the Log method on ILogger, ExceptionTelemetry is created instead of TraceTelemetry. These telemetry items can be found in the same places as any other TraceTelemetry or ExceptionTelemetry items for Application Insights, including the Azure portal, analytics, or the Visual Studio local debugger.
Please follow the steps as below for your asp .net core application. I'm using .net core 3.1 web application for this test.
1.Please follow this article to configure application insights from visual studio. Note, after the configuration is completed, update the Microsoft.ApplicationInsights.AspNetCore
to the latest version 2.14.0.
2.In the appsettings.json
file, use the following settings(by default, only warning level or higher are logged by application insights). Note: please also remember right click this file -> select properties -> then set the "copy to output directory" as "copy if newer".
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"InstrumentationKey": "the key"
}
}
3.In Startup.cs -> ConfigureServices method, check if the code looks like below:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
}
4.In your Controller, use the like code below:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("222 this is a information message...");
_logger.LogWarning("222 this is a warning message...");
return View();
}
}
5.Then in the azure portal -> your application insights -> logs, you can see the telemetry data are logged in traces table:
Please let me know if you still have more issues about this:).
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