2017-01-16 64 views
7

在老ASP.NET,在Global.asax.cs類,我會當應用程序啓動,停止,並拋出未處理的異常日誌我在ASP.NET Core中也是這樣做的嗎?它有一個Startup類,但它用於配置。我可以在哪裏登錄ASP.NET Core應用程序的開始/停止/錯誤事件?</p> <ul> <li><code>Application_Start()</code></li> <li><code>Application_End()</code></li> <li><code>Application_Error()</code></li> </ul> <p>怎麼辦:

我在哪裏掛鉤應用程序的開始/停止/錯誤事件?

回答

9

您需要使用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; 
    } 
} 
+0

是否有未處理的異常相似的地方? – grokky

+0

這些方法[可以使用](https://stackoverflow.com/a/35257670/7059613)來檢測開始/停止/停止。但是,你將如何在那裏登錄?記錄器的實例不能被檢索,因爲你在'Startup'類中? – grokky

+0

@grokky已更新答案 – Set

1

請參閱CaptureStartupErrors和方法.CaptureStartupErrors(true),這將有助於你找到問題。

當某些東西在localhost上完美運行但在Azure中失敗時,這特別方便。

這裏是我的磊科網絡應用通常的配置:

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

在Azure的應用程序服務,您可以再找到日誌流中的日誌中捻工具https://<appname>.scm.azurewebsites.net/api/logstream