Reputation:
I'm having trouble starting a worker service using the serilog logger with the ConfigurationBuilder to pull json settings from the appsettings.json. When the service is started it fails for "Error 1053: The service did not respond to the start...", but works as a console app. If I remove the ConfigurationBuilder code and use the old way to initialize the logger it works great to start the service and run as a console app. Can anyone see a problem with my code below that I grabbed from the serilog gitHub for the ConfigurationBuilder method to load from appsettings.json. Maybe it's a .Net 5 problem or something.
This code below fails to start as a service, but works as a console app.
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
return;
}
catch (Exception ex)
{
Log.Fatal("Error starting service - " + ex.ToString());
return;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
}).UseSerilog();
}
appsettings.json file
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:/repoLog.txt",
"rollingInterval": "Day"
}
}
]
}
}
This method works great below in console mode and the service starts fine, so it something with my ConfigurationBuilder or SetBasePath(Directory.GetCurrentDirectory() when the service starts.
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.File("C:/repoLog.txt")
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
return;
}
catch (Exception ex)
{
Log.Fatal("Error starting service - " + ex.ToString());
return;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
}).UseSerilog();
}
Upvotes: 0
Views: 3444
Reputation:
For what it's worth, the core service loading problem was resolved by using this ConfigurationBuilder format. The logger now works as a service and a console app.
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Upvotes: 0