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

后端 未结 4 1570
孤独总比滥情好
孤独总比滥情好 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 16:59

    I didn't like @neustart47 answer as it was unnecessarily complex but he is right that IApplicationLifetime is obsolete.

    Taken from the Microsoft Docs

    //  1. Add the interface `IHostedService` to the class you would like
    //     to be called during an application event. 
    internal class LifetimeEventsHostedService : IHostedService
    {
        private readonly ILogger _logger;
        private readonly IHostApplicationLifetime _appLifetime;
    
        // 2. Inject `IHostApplicationLifetime` through dependency injection in the constructor.
        public LifetimeEventsHostedService(
            ILogger logger, 
            IHostApplicationLifetime appLifetime)
        {
            _logger = logger;
            _appLifetime = appLifetime;
        }
    
        // 3. Implemented by `IHostedService`, setup here your event registration. 
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _appLifetime.ApplicationStarted.Register(OnStarted);
            _appLifetime.ApplicationStopping.Register(OnStopping);
            _appLifetime.ApplicationStopped.Register(OnStopped);
    
            return Task.CompletedTask;
        }
    
        // 4. Implemented by `IHostedService`, setup here your shutdown registration.
        //    If you have nothing to stop, then just return `Task.CompletedTask`
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    
        private void OnStarted()
        {
            _logger.LogInformation("OnStarted has been called.");
    
            // Perform post-startup activities here
        }
    
        private void OnStopping()
        {
            _logger.LogInformation("OnStopping has been called.");
    
            // Perform on-stopping activities here
        }
    
        private void OnStopped()
        {
            _logger.LogInformation("OnStopped has been called.");
    
            // Perform post-stopped activities here
        }
    }
    

    Done!

提交回复
热议问题