Home > Software engineering >  Console application not logging error with NLOG in AppDomain.CurrentDomain.UnhandledException
Console application not logging error with NLOG in AppDomain.CurrentDomain.UnhandledException

Time:03-16

The below code isn't logging to my database. Is it because the console application closes too soon and if so how can I prevent this?

   private static ILogger _logger;

      static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            _logger.Error((Exception)e.ExceptionObject);
        }
    
        private static void Main(string[] args)
        {
            var container = new Container();
            _logger = container.GetInstance<ILogger>();
    AppDomain.CurrentDomain.UnhandledException  = UnhandledExceptionTrapper;
            throw new Exception("test");

CodePudding user response:

You can call LogManager.Shutdown() before leaving your UnhandledExceptionTrapper method. This calls internally LogManager.Flush() which

Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds.

see nlog db entries example

  • Related