Where to call Serilog CloseAndFlush (Asp.Net Web Api 4.8)

We’re trying to setup add an instance of hangfire with serilog to our api but serilog say that Log.CloseAndFlush should be called when the application is shutting down in order to ensure all sinks finish writing.

When adding this to the default owin OnAppDisposing event it’s called before the job server notifies any jobs that it’s shutting down so nothing is logged.

With the following in Startup.cs

new AppProperties(app.Properties).OnAppDisposing.Register(Log.CloseAndFlush);

The log looks like:

09 Nov 2021 09:35:43.430 Starting Hangfire Server using job storage: ‘SQL Server: sqldev’

09 Nov 2021 09:35:41.615 Job server starting…

09 Nov 2021 09:35:41.621 Long running current count: 28

09 Nov 2021 09:35:38.618 Long running current count: 27

09 Nov 2021 09:35:35.606 Long running current count: 26

But without ever calling CloseAndFlush() the log looks like:

09 Nov 2021 09:30:34.912 Starting Hangfire Server using job storage: ‘SQL Server: sqldev’

09 Nov 2021 09:30:34.869 Job server starting…

09 Nov 2021 09:30:34.728 HostingEnvironment.ShutdownReason shutdown trigger initialized successfully.

09 Nov 2021 09:30:34.727 HostingEnvironment.StopListening shutdown trigger initialized successfully.

09 Nov 2021 09:30:33.632 Received shutdown notification: 10

09 Nov 2021 09:30:30.610 Long running current count: 9

09 Nov 2021 09:30:30.610 Long running current count: 9

09 Nov 2021 09:30:27.605 Long running current count: 8

09 Nov 2021 09:30:24.605 Long running current count: 7

09 Nov 2021 09:30:21.605 Long running current count: 6

Our hangfire setup looks like:

public static void ConfigureHangfire(IAppBuilder app, IContainer container)
{
GlobalConfiguration.Configuration.UseSerilogLogProvider();

app.UseHangfireAspNet(GetHangfireServers);
app.UseHangfireDashboard("/dashboard", GetDashboardOptions());

}

Is there some part of the hangfire shutdown itself that we can hook into and only flush the log once hangfire has finished disposing?