gpt4 book ai didi

c# - 在哪里可以记录 ASP.NET Core 应用程序的启动/停止/错误事件?

转载 作者:可可西里 更新时间:2023-11-01 03:06:44 26 4
gpt4 key购买 nike

在旧的 ASP.NET 中,在 Global.asax.cs 类中,我会记录应用程序启动、停止和抛出未处理异常的时间:

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

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

我在哪里 Hook 到应用程序的启动/停止/错误事件?

最佳答案

注意:对于 .NET Core 3.0 或更高版本,此答案已过时。参见 this answer相反。

您需要使用 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; }

IApplicationLifetime 的实例可以在Configure 方法中获得。还要在此处添加 ILoggerFactory:

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

拥有ILoggerFactory,您可以create ILogger 实例:

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

所以你只需要在 Startup 类中创建一个属性来持久化 ILogger(或 ILoggerFactory,如果你想为不同的 ligger 实例创建不同的实例)事件)。总结:

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

关于c# - 在哪里可以记录 ASP.NET Core 应用程序的启动/停止/错误事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com