Where can I log ASP.NET Core application start / stop / error events?

In the old ASP.NET, in the Global.asax.cs class, I have to register when the application starts, stops and throws unhandled exceptions:

  • Application_Start()
  • Application_End()
  • Application_Error()

How to do the same in ASP.NET Core? It has a Startup class, but it is intended for configuration.

Where can I connect to application start / stop / error events?

+7
c # asp.net-core
source share
2 answers

You need to use Microsoft.AspNetCore.Hosting.IApplicationLifetime

  /// <summary> /// Triggered when the application host has fully started and is about to wait /// for a graceful shutdown. /// </summary> CancellationToken ApplicationStarted { get; } /// <summary> /// Triggered when the application host is performing a graceful shutdown. /// Requests may still be in flight. Shutdown will block until this event completes. /// </summary> CancellationToken ApplicationStopping { get; } /// <summary> /// Triggered when the application host is performing a graceful shutdown. /// All requests should be complete at this point. Shutdown will block /// until this event completes. /// </summary> CancellationToken ApplicationStopped { get; } 

An instance of IApplicationLifetime can be obtained in the Configure method. Also add an ILoggerFactory here:

 public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { // use applicationLifetime } 

With an ILoggerFactory , you can instantiate an ILogger :

 var logger = loggerFactory.CreateLogger("StartupLogger"); 

Therefore, you just need to create a property in the Startup class to save an instance of ILogger (or ILoggerFactory if you want to create another instance of ligger for different events). Summarizing:

 public class Startup { private ILogger _logger; public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { applicationLifetime.ApplicationStopping.Register(OnShutdown); ... // add logger providers // loggerFactory.AddConsole() ... _logger = loggerFactory.CreateLogger("StartupLogger"); } private void OnShutdown() { // use _logger here; } } 
+9
source share

Please see CaptureStartupErrors and the .CaptureStartupErrors(true) method to help you find problems.

This is especially convenient when something works fine on localhost but doesn't work on Azure.

Here is my usual configuration for NetCore Web Apps:

 public static IWebHost BuildWebHost(string[] args) => WebHost .CreateDefaultBuilder(args) .CaptureStartupErrors(true) .UseKestrel() .UseIISIntegration() .UseStartup<Startup>() .UseAzureAppServices() .Build(); 

In the Azure App Service, you can find the logs in the log stream in Kudu Tools https://<appname>.scm.azurewebsites.net/api/logstream

+1
source share

All Articles