I am using Application Insights in my ASP.NET Core 2.1 REST Backend which works fine to track errors during normal execution. However when i am having a problem during startup of the application (for example missing configurations), the process crashes and the exception ends up in IIs which displays a generic error page.
I found out i can control this behavior by setting the Environment Variable ASPNETCORE_CAPTURESTARTUPERRORS as described here to get a detailed error page.
But i want this detailed error to be tracked in application insights and eventually control the availability setting of the application if such an error occurs.
Does anybody know how to achieve this?
Update 0416: Adding the solution provided by op:
by wrapping CreateWebHostBuilder(args).Build().Run();
in a try/catch
block and sending the exception directly using TelemetryClient
.
Update:
For ASP.NET core 2.1, it is possible(verified at my side, note: no need to use ILogger here, it can auto-collect the unhandled exceptions in program.cs or startup.cs). You can add the following code in the Program.cs:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(
builder =>
{
builder.AddApplicationInsights("ikey");
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
(typeof(Program).FullName, LogLevel.Trace);
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
(typeof(Startup).FullName, LogLevel.Trace);
}
);
For more details, you can refer to this article.
Original answer:
Unfortunately, log errors during startup
is not supported.
Here is the official doc, and it states:
There are a number of cases that the exception filters cannot handle. For example:
1.Exceptions thrown from controller constructors.
2.Exceptions thrown from message handlers.
3.Exceptions thrown during routing.
4.Exceptions thrown during response content serialization.
5.Exception thrown during application start-up.
6.Exception thrown in background tasks.