如何在执行 Environment.Exit() 之前刷新 dotnet core 应用程序中的所有记录器

Ale*_*lex 8 c# .net-core asp.net-core

基本上,我遇到了应用程序崩溃并且没有调试日志的老问题,因为应用程序在写入日志之前就终止了。

经典的方法是捕获 main 中的所有异常并刷新异常块中的所有日志缓冲区。此外,添加睡眠以降低重新启动速度并允许缓冲区完成刷新。

我使用serilog,我找到了这张票:https ://github.com/serilog/serilog/issues/1111

它建议按照我的建议进行操作(下面粘贴的代码),但我不确定它会关闭并刷新所有记录器,而不仅仅是主记录器。

  1. 我是否需要刷新更多记录器才能获取所有日志?
  2. 此示例假设,ConfigureLogging() 设置记录器,但在真正的 asp .netcore main 中,您通常没有设置记录器,我该如何做到这一点?
public static int Main(string[] args)
{
    ConfigureLogging(); // set up Serilog

    try
    {
        Log.Logger.Information("Custom.API Server is starting.");
        var webHost = BuildWebHost(args);
        webHost.Run();

        Log.Logger.Information("Custom.API Server is starting.");
        return 0;
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Host terminated unexpectedly.");
        return 1;
    }
    finally
    {
        Log.CloseAndFlush();
        Thread.Sleep(2000); // give serilog / seq time to flush the messages
    }
}
Run Code Online (Sandbox Code Playgroud)