[英]How to save Serilog event logs before a database is created by the app?
I created a logger successfully using Serilog but I can't determine how to tell if the SQL Server database I'm logging to exists before I create the logger.我使用 Serilog 成功创建了一个记录器,但在创建记录器之前,我无法确定如何判断我要记录到的 SQL Server 数据库是否存在。 The goal is to create the logger before this line in my Main function so I get all of the startup logs:
目标是在我的 Main 函数中的这一行之前创建记录器,以便我获得所有启动日志:
var host = CreateHostBuilder(args).Build();
However, if I do that, and the database doesn't exist yet, the logging table won't get created the first time I start the application.但是,如果我这样做,并且数据库尚不存在,则在我第一次启动应用程序时将不会创建日志记录表。 It will get created the second time I start the application because I'm creating and seeding the database after that line of code.
它将在我第二次启动应用程序时创建,因为我在该行代码之后创建和播种数据库。
I want to create the logger before CreateHostBuilder runs if the database exists or create the logger after CreateHostBuilder and SeedDatabase run if the database doesn't exist yet.如果数据库存在,我想在 CreateHostBuilder 运行之前创建记录器,或者如果数据库尚不存在,则在 CreateHostBuilder 和 SeedDatabase 运行之后创建记录器。 I can't run CreateLogger() twice either or I'll get an exception.
我也不能运行 CreateLogger() 两次,否则会出现异常。
Here is the code:这是代码:
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 after adding file logging:添加文件日志后更新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.