Timo1995
Timo1995

Reputation: 137

Logging Fatal Exception

Im trying to log an exception when my application crashes. Despite catching most exceptions every once in a while my app crashes. And I cant really figure out how to log the exception to a textfile. Whatever I try doesnt seem to work. Im not sure what Im doing wrong and would appreciate if someone could point me in the right direction.

This is how my code currently looks. And Im using a multithreaded environment.

        public MainWindow()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
            InitializeComponent();          
        }

        static void MyHandler(object sender, UnhandledExceptionEventArgs args)
        {
            Exception e = (Exception)args.ExceptionObject;
            using (StreamWriter writer = File.AppendText("ExceptionsLog.txt"))
            {
                DateTime time = DateTime.Now;
                writer.WriteLine("Time {0} Exception: {1} Runtime termination: {2}", time, e.Message, args.IsTerminating);
            }
        }

Upvotes: 2

Views: 1005

Answers (1)

Athari
Athari

Reputation: 34275

First, make sure to flush your StreamWriter.

Second, there may be other exceptions which aren't reported by AppDomain.CurrentDomain.UnhandledException.

  • If you're using tasks, they may cause TaskScheduler.UnobservedTaskException event to fire.

  • If you're using WPF, you may also want to handle Application.Current.DispatcherUnhandledException event which allows to prevent process from crashing.

  • If you're using multiple app domains, exceptions in them aren't handled by the current domain.

Upvotes: 3

Related Questions