Reputation: 265
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. The goal is to create the logger before this line in my Main function so I get all of the startup logs:
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. I can't run CreateLogger() twice either or I'll get an exception.
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:
"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"
}
}
]
}
}
}
Upvotes: 0
Views: 856
Reputation: 1611
Do some fallback logic in CreateLogger that it logs into file if database doesn't exists and after db is created, if it needed to be created, you can write those log file content into db.
Upvotes: 1