Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I log an ASP.NET Core app's start/stop/error events?

In old ASP.NET, in the Global.asax.cs class, I would log when the app starts, stops and throws unhandled exceptions:

  • Application_Start()
  • Application_End()
  • Application_Error()

How do I do the same in ASP.NET Core? It has a Startup class, but it is for configuration.

Where do I hook into the app's start/stop/error events?

like image 841
grokky Avatar asked Jan 16 '17 11:01

grokky


People also ask

What is logger in ASP.NET Core?

In ASP.NET Core, logging providers store the logs. You can configure multiple logging providers for your application. The default ASP.NET Core configures the following logging providers: Console, Debug, EventSource, and EventLog (on Windows).


1 Answers

Note: For .NET Core 3.0 or later, this answer is obsolete. See this answer instead.

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; } 

Instance of IApplicationLifetime could be obtained in Configure method. Also add ILoggerFactory here:

public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) {     // use applicationLifetime } 

Having ILoggerFactory, you can create instance of ILogger:

var logger = loggerFactory.CreateLogger("StartupLogger");  

So you just need to create a property in the Startup class to persist the instance of ILogger (or ILoggerFactory, if you would like to create different ligger instance for different events). To summarize:

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;     } } 
like image 116
Set Avatar answered Sep 20 '22 18:09

Set