Reputation: 275
I am creating a Windows Service using a .Net Core 6 Worker project.
I have added Setilog which is working, and I have settings in appsettings.json. However, I would like to write to the log file when starting and stopping the service. I have the following code in program.cs, which seems to work, but this does not make use of the settings in appsettings.json. Is it possible to get the settings from appsettings.json instead of adding them to this initial Serilog setup?
using Serilog;
using Serilog.Events;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File("./logs/log-.txt", rollingInterval:RollingInterval.Day)
.CreateBootstrapLogger();
try
{
Log.Information("Starting the Service");
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSerilog()
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "There was a problem starting the service");
return;
}
finally
{
Log.Information("Service successfully stopped");
Log.CloseAndFlush();
}
Upvotes: 3
Views: 10278
Reputation: 131492
This looks like part of the code used for two-stage initialization. CreateBootstrapLogger()
is used to create a logger that can be used only until .NET Core's logging infrastructure is configured and functional.
using Serilog;
using Serilog.Events;
public class Program
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
The Two-stage initialization docs show how to read settings using ReadFrom.Configuration
in the main logger configuration :
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Upvotes: 3