Topshelf NLog Ensure Flush

242 Views Asked by At

I have seen code examples that look like this to ensure that if your application crashes, your logs get written. I understand this and the variations of the code shown below.

public static void Main(string[] args)
    {
        // NLog: setup the logger first to catch all errors
        var logger = LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            BuildWebHost(args).Run();
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

However, Topshelf recommends implementing logging with NLog like this:

HostFactory.New(x =>
{
    x.UseNLog();
});

Does the code:

x.UseNLog();

ensure that logs are written when the service fails/crashes ungracefully? i.e. does it implement behind the scenes:

// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();

Alternatively, where should I implement this code?

1

There are 1 best solutions below

0
ice-beam On

From what I can see here in Github, UseNLog will cause a call to NLog.LogManager.Shutdown():

    public class NLogLogWriterFactory :
        LogWriterFactory
    {
...
        public void Shutdown()
        {
            _logFactory.Flush();
            _logFactory.SuspendLogging();
            
            LogManager.Shutdown();
        }
...
    }

(LogWriterFactory is an interface here, and Shutdown is an implementation of the corresponding method of this interface).

According to tags, the commit should be present in all versions of Topshelf NuGet package starting from 4.3.0. So no need to call NLog.LogManager.Shutdown() manually.