您需要使用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; }
IApplicationLifetime的實例可以在Configure
方法獲得。另外補充ILoggerFactory這裏:
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
// use applicationLifetime
}
有ILoggerFactory
,你可以的create實例:
var logger = loggerFactory.CreateLogger("StartupLogger");
所以,你只需要創建的啓動類的屬性堅持的實例(或ILoggerFactory
,如果你想爲不同的事件創建不同的ligger實例)。總結:
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;
}
}
來源
2017-01-16 12:02:19
Set
是否有未處理的異常相似的地方? – grokky
這些方法[可以使用](https://stackoverflow.com/a/35257670/7059613)來檢測開始/停止/停止。但是,你將如何在那裏登錄?記錄器的實例不能被檢索,因爲你在'Startup'類中? – grokky
@grokky已更新答案 – Set