我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件? [英] Where can I log an ASP.NET Core app's start/stop/error events?

查看:548
本文介绍了我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在旧的ASP.NET中,在Global.asax.cs类中,我会在应用程序启动,停止并引发未处理的异常时记录日志:

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()
  • Application_Start()
  • Application_End()
  • Application_Error()

如何在ASP.NET Core中执行相同的操作?它具有Startup类,但用于配置.

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?

推荐答案

您需要使用 IApplicationLifetime的

实例可以通过Configure方法获得.还可以在此处添加ILoggerFactory:

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

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

具有ILoggerFactory,您可以创建实例ILogger:

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

因此,您只需要在Startup类中创建一个属性来保留ILogger(或ILoggerFactory,如果您想为不同的事件创建不同的ligger实例)实例即可.总结一下:

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

这篇关于我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆