在旧的ASP.NET中,在Global.asax.cs
类中,我会在应用程序启动时记录,停止并抛出未处理的异常:
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; }
IApplicationLifetime的实例可以通过Configure
方法获得.另外在这里添加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和.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工具中的日志流中找到日志 https://