I am writing a worker service that needs to use Serilog and write to a log file. (.net core 6 and Windows service). The same service, when using Microsoft.Extensions.Logging and writing event logs as configured in aspsettings.json, logs to the event log just fine. Also, I've proven that I have access to the directory where the logs are being written.
When I configure the project to use Serilog to write to a log file, the log file is never written to (and if it doesn't exist, it is not created). I'd love any input you might have on why the log file is not created.
Nuget packages
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
Program.cs
using Serilog;
using WorkerServiceAndSerilog;
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((builderContext, config) =>
{
config.SetBasePath(System.AppDomain.CurrentDomain.BaseDirectory);
})
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.AddLogging(configure => configure.AddSerilog());
})
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.Build();
var logger = host.Services.GetService<ILogger<Program>>();
logger!.LogInformation($"Before host.RunAsync");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path: @"c:\POC\logs\accessProof.txt", true))
file.WriteLine($"We're Running WorkerServiceAndSerilog {DateTime.Now}");
await host.RunAsync();
My app settings are configured to write to Console and to File, with file using the Json formatter. The app settings are being loaded. Before adding Serilog, I was loading app settings that configured event logging which was successful. SetBasePath was the key to getting that working.
Snippet from appsettings.json
"Serilog": {
"Enable": true,
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"System": "Error",
"Microsoft": "Verbose",
"Microsoft.AspNetCore": "Verbose",
"Microsoft.EntityFrameworkCore": "Information"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "Console",
"Args": {
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:MM-dd HH:mm:ss.ffff} | {Level:u3} | {MachineName} | {RequestId} | {Assembly} | {Version} | {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"restrictedToMinimumLevel": "Information",
"path": "\\POC\\logs\\WS.log",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"buffered": true,
"flushToDiskInterval": "00:00:02",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}