Is it possible to log ApplicationBuilder configuration failure?

1 week ago 12
ARTICLE AD BOX

Yes, but not using DI. You'll need to try/catch or use AppDomain.UnhandledException (or both!) - and you'll also need to handle the case when NLog itself fails to initialize (I recommend Environment.FailFast):

static class Program { private static ILogger? _entrypointLogger; static Int32 Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; try // <-- This try/catch over the `_entrypointLogger` assignment can be omitted if you're okay with the fallback in `OnUnhandledException`. { _entrypointLogger = LoggerFactory.Create(builder => builder.AddNLog()).CreateLogger<Program>(); } catch(Exception ex) { Environment.FailFast( $"Unhandled {ex.GetType().FullName} in Program.Main while initializing NLog: " + ex.Message, e.Exception ); return 1; } // IHost host; try { var builder = Host.CreateApplicationBuilder(args); builder.UseNLog(); builder.Services.AddWindowsService(); builder.Services.AddMetrics(c=> throw new Exception("WTF")); host = builder.Build(); } catch(Exception ex) { _entrypointLogger.LogError( exception: ex.Exception, $"Unhandled {ex.GetType().FullName} in Program.Main during ApplicationBuilder configuration: {ExMessage}", ex.Message ); return 1; } host.Run(); return 0; } private static void OnUnhandledException(Object? sender, UnhandledExceptionEventArgs e) { ILogger? log = _entrypointLogger; // Create a local reference for thread-safety. if( log is null ) { Environment.FailFast( "Unhandled exception in AppDomain when NLog is unavailable.", e.Exception ); } else { log.LogError( exception: e.Exception, "Unhandled exception in AppDomain: {ExMessage}", e.Exception.Message ); } } }

Dai's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article