如何在应用程序创建数据库之前保存 Serilog 事件日志?

How to save Serilog event logs before a database is created by the app?

我使用 Serilog 成功创建了一个记录器,但我无法确定在创建记录器之前如何判断我正在记录的 SQL 服务器数据库是否存在。目标是在我的 Main 函数中的这一行之前创建记录器,以便我获得所有启动日志:

var host = CreateHostBuilder(args).Build();

但是,如果我这样做,并且数据库尚不存在,则在我第一次启动应用程序时不会创建日志记录 table。它会在我第二次启动应用程序时创建,因为我在该行代码之后创建和播种数据库。

如果数据库存在,我想在 CreateHostBuilder 运行 之前创建记录器,如果数据库尚不存在,我想在 CreateHostBuilder 和 SeedDatabase 运行 之后创建记录器。我也不能 运行 CreateLogger() 两次,否则我会得到一个异常。

代码如下:

public static void Main(string[] args)
{
    try
    {
        // If I create the logger here I'll see all the startup logs
        // if the database exists. If the database doesn't exist yet the 
        // logging table won't get created until the second time I startup the app.
        CreateLogger();

        Log.Information("Starting Up");

        var host = CreateHostBuilder(args).Build();

        SeedDatabase(host);

        // If I create the logger here I don't get all of the startup logs but
        // it ensures that if the database hasn't been created and seeded yet the 
        // logging table is still created.
        CreateLogger();

        host.Run();
    }
    catch (Exception exception)
    {
        Log.Fatal(exception, "Application start-up failed");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

public static void CreateLogger()
{
    Log.Logger = new LoggerConfiguration()
        // Add/Update configuration settings in appsettings.json.
        // Don't add them here.
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();
}

UPDATED appsettings.json 添加文件日志后:


"Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "DbContext",
          "tableName": "EventLog",
          "autoCreateSqlTable": true
        }
      }
    ],
    "WriteTo:Async": {
      "Name": "Async",
      "Args": {
        "configure": [
          {
            "Name": "File",
            "Args": {
              "path": "../../EventLogs/",
              "rollingInterval": "Day"
            }
          }
        ]
      }
    }
  }

在CreateLogger中做一些回退逻辑,如果数据库不存在它会记录到文件中,并且在创建db之后,如果需要创建它,则可以将这些日志文件内容写入db。