我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?
在旧的ASP.NET中,在Global.asax.cs
类中,我会在应用程序启动时停止,停止并抛出未处理的exception:
-
Application_Start()
-
Application_End()
-
Application_Error()
我如何在ASP.NET Core中执行相同的操作? 它有一个Startup
类,但它用于配置。
我在哪里挂钩应用程序的开始/停止/错误事件?
您需要使用Microsoft.AspNetCore.Hosting.IApplicationLifetime
/// /// Triggered when the application host has fully started and is about to wait /// for a graceful shutdown. /// CancellationToken ApplicationStarted { get; } /// /// Triggered when the application host is performing a graceful shutdown. /// Requests may still be in flight. Shutdown will block until this event completes. /// CancellationToken ApplicationStopping { get; } /// /// 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. /// CancellationToken ApplicationStopped { get; }
可以在Configure
方法中获取IApplicationLifetime的实例。 另外在这里添加ILoggerFactory:
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { // use applicationLifetime }
有了ILoggerFactory
,你可以创建 ILogger
实例:
var logger = loggerFactory.CreateLogger("StartupLogger");
因此,您只需要在Startup类中创建一个属性来持久化ILogger
的实例(或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; } }
请参阅.CaptureStartupErrors(true)
和方法.CaptureStartupErrors(true)
,它将帮助您查找问题。
当某些东西在localhost上运行完美但在Azure中失败时,这尤其方便。
这是我常用的NetCore Web Apps配置:
public static IWebHost BuildWebHost(string[] args) => WebHost .CreateDefaultBuilder(args) .CaptureStartupErrors(true) .UseKestrel() .UseIISIntegration() .UseStartup() .UseAzureAppServices() .Build();
在Azure App Service中,您可以在Kudu Tools中找到日志流中的日志https://