在由应用创建数据库之前保存Serilog事件日志的最佳做法?

问题描述 投票:0回答:1

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

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

但是,如果我这样做了,并且数据库还不存在,那么在我第一次启动应用程序时就不会创建日志表。它将在我第二次启动应用程序时创建,因为在该行代码之后我正在创建数据库并为其添加种子。

如果数据库存在,我想在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" } } ] } } }
c# sql-server asp.net-core serilog
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.