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

后端 未结 4 1568
孤独总比滥情好
孤独总比滥情好 2020-12-14 16:24

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

  • Application_Start()
4条回答
  •  隐瞒了意图╮
    2020-12-14 17:19

    You need to use 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; }
    

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

提交回复
热议问题