I have created a Worker Service using C# / .Net Core 6 (Visual Studio 2022).
It writes to a log file as expected if run via Visual Studio or started directly from Windows Explorer / PowerShell. However, when installed as a Windows Service, it does not create or write to a log file.
This is my program.cs:
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()
.ConfigureAppConfiguration((hostContext, configBuilder) =>
{
configBuilder
//.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.MachineName}.json", true, true)
.Build();
})
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext())
.ConfigureServices((hostContext, services) =>
{
...
})
.Build();
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "There was a problem starting the service");
}
finally
{
Log.Information("Service successfully stopped");
Log.CloseAndFlush();
}
I have this in appsettings.json:
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Debug" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": ".\\logs\\log-.txt",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext" ]
}
If I include the "SetBasePath" part, the service fails to start (although it still runs via Visual Studio).
I am publishing the service from Visual Studio with Target Framework = net6.0, Deployment Mode = Framework Dependent, Target runtime = win-x64.
Note: I have created a Logger in Program.cs because I wanted to log the start and stop / crash of the service.
svchost
process. It's quite likely your logs are in System32. Use an absolute path instead, preferably one based on configuration settings – Haplology