[英]How to save Serilog event logs before a database is created by the app?
我使用 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();
}
添加文件日志后更新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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.