How do I register Serilog with ILogger in older Windows Service application?


I have a Windows Service that I am trying to upgrade to use dependency injection and Serilog.

This is not a .net core windows service. This is the older style with ServiceBase

Below is my setup code for the logger.

public static IServiceProvider ConfigureServices()
var services = new ServiceCollection();

Log.Logger = new LoggerConfiguration()

// app starts fine if I remove below line
services.AddLogging(builder => builder.AddSerilog());

return services.BuildServiceProvider();

Here is the OnStart from my ServiceBase

protected override void OnStart(string[] args)
  Log.Information("Starting Service");
  Task.Run(async () =>
    var provider = Startup.ConfigureServices();
    Log.Information("Done configuring provider");
    supervisor = new Supervisor(provider);
    await supervisor.Run();
  catch (Exception e)

When I startup the service I get the "Starting Service" message, but not "Done configuring provider" message. Then the app immediately crashes with this error

Faulting application name: MyWindowsService.exe, version:, time stamp: 0x606f3be8
Faulting module name: clr.dll, version: 4.7.3750.0, time stamp: 0x5fbc74bf
Exception code: 0xc0000005
Fault offset: 0x000184bd
Faulting process id: 0x13d0
Faulting application start time: 0x01d72c9c4fdd7bea
Faulting application path: C:\Program Files\MyWindowsService\MyWindowsService.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Report Id: f5fdda16-5491-4eb2-b5df-878c11b08b5c
Faulting package full name: 
Faulting package-relative application ID: 

I tried changing the dispose value between true and false for AddSerilog and that didn't do anything. Also tried doing AddLogging(). Then getting the LoggerFactory from the provider and calling AddSerilog on that.

Commenting out services.AddLogging(builder => builder.AddSerilog()); allows the app to run without issue, just no ILogger logging.

My backup plan is to either call the static serilog Log for now. Or go through the effort of updating the project to the new Windows Service HostBuilder stuff.

How do I get Serilog to register with ILogger/ILoggerFactory so I can use it with this windows service?


1 Answer


I couldn't determine what was causing the issue. But dumping the older style windows service in favor of Microsoft.Extensions.Hosting.WindowsServices got rid of the issue, so it was easier to just convert the project.

answered on Stack Overflow Apr 19, 2021 by KaijuuLambdaFighter

User contributions licensed under CC BY-SA 3.0