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?
From what I can see here in Github,
UseNLogwill cause a call toNLog.LogManager.Shutdown():(
LogWriterFactoryis an interface here, andShutdownis 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 callNLog.LogManager.Shutdown()manually.