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) {
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); ...
Set
source share