Home > Software design >  ASP.NET Core how to do something before shutdown/on fatal error?
ASP.NET Core how to do something before shutdown/on fatal error?

Time:06-25

I have ASP.NET server. I would like to log fatal error, that crashes server. And save in database some information about this fatal error. What should I use? I thought about IHostApplicationLifetime, but it's used for graceful shutdown and not for fatal errors.

CodePudding user response:

if you use serilog you could do something like this

public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore",LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                .WriteTo.File(new JsonFormatter(),"\logs\serilog.json", shared: true)
               .CreateLogger();

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.UseSerilog();
            });
    }
  • Related