受欢迎的博客标签

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

Published

Table of Contents

 

.Net 6.x

Microsoft.Extensions.Hosting->IHostApplicationLifetime 

#region 程序集 Microsoft.Extensions.Hosting.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\6.0.0\ref\net6.0\Microsoft.Extensions.Hosting.Abstractions.dll
// Decompiled with ICSharpCode.Decompiler 6.1.0.5902
#endregion

using System.Threading;

namespace Microsoft.Extensions.Hosting
{
   
    public interface IHostApplicationLifetime
   {
        CancellationToken ApplicationStopped
      
        CancellationToken ApplicationStopping
       
        void StopApplication();
    }
}

 

program.cs

Step 1:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IService, Service>();

var app = builder.Build();

IService service = app.Services.GetRequiredService<IService>();
ILogger logger = app.Logger;
IHostApplicationLifetime lifetime = app.Lifetime;
IWebHostEnvironment env = app.Environment;

lifetime.ApplicationStarted.Register(() =>
    logger.LogInformation($"The application {env.ApplicationName} started in we injected {service}"));

app.Run();

Step 2:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IService, Service>();

var app = builder.Build();

IService service = app.Services.GetRequiredService<IService>();

ILogger logger = app.Logger;
IHostApplicationLifetime lifetime = app.Lifetime;
IWebHostEnvironment env = app.Environment;

logger.LogInformation($"{DateTime.Now} app start...");

lifetime.ApplicationStarted.Register(() =>
    logger.LogInformation($"{DateTime.Now}The application {env.ApplicationName} started in we injected "));
lifetime.ApplicationStopped.Register(OnStopped);

app.Run();

void OnStopped()
{
  

    app.Logger.LogInformation($"{DateTime.Now} OnStopped has been called.");

   
}

output

dbug: Microsoft.Extensions.Hosting.Internal.Host[2]
      Hosting started
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
dbug: Microsoft.Extensions.Hosting.Internal.Host[3]
      Hosting stopping
info: Nop.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null[0]
      2022/5/13 0:30:11 OnStopped has been called.
dbug: Microsoft.Extensions.Hosting.Internal.Host[4]
      Hosting stopped

Net 5.x

 

step 1:use Microsoft.AspNetCore.Hosting.IApplicationLifetime

 

step 2: startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IHostApplicationLifetime appLifetime)
        {

            /// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-6.0#ihostapplicationlifetime
            /// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-5.0#ihostapplicationlifetime
            appLifetime.ApplicationStarted.Register(OnStarted);
            appLifetime.ApplicationStopping.Register(OnStopping);
            appLifetime.ApplicationStopped.Register(OnStopped);

 

  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
        }

 

Useful links

https://stackoverflow.com/questions/41675577/where-can-i-log-an-asp-net-core-apps-start-stop-error-events

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-6.0#ihostapplicationlifetime


        https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-5.0#ihostapplicationlifetime