我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件? [英] Where can I log an ASP.NET Core app's start/stop/error events?
问题描述
在旧的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的 实例可以通过 Instance of IApplicationLifetime could be obtained in 具有 因此,您只需要在Startup类中创建一个属性来保留 So you just need to create a property in the Startup class to persist the instance of 这篇关于我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Configure
方法获得.还可以在此处添加ILoggerFactory:Configure
method. Also add ILoggerFactory here:public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
// use applicationLifetime
}
ILoggerFactory
,您可以创建实例ILogger
:var logger = loggerFactory.CreateLogger("StartupLogger");
ILogger
(或ILoggerFactory
,如果您想为不同的事件创建不同的ligger实例)实例即可.总结一下: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;
}
}