Reputation: 870
How can I write the stack trace of an unhandled exception (thrown from any thread) to a file?
I need this to help debug a hanging application.
Upvotes: 5
Views: 643
Reputation: 870
Thanks you all, but I have seen that when I running the program from Visual Studio the output of trace that is written by .NET to the console window when an unhandled exception from any thread is thrown is not redirected to the console window.
It is just redirected when I run the program separated from Visual Studio. So this code is very good to see all stack trace from any thread that throws an exception which is not handled
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Environment.CurrentDirectory, "logfile.txt"));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime | TraceOptions.Callstack;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
Upvotes: 1
Reputation: 1959
You can get the stack track in catch block by ex.StackTrace like below:
try
{
//Your code;
}
catch(Exception ex)
{
string innerException = ex.InnerException;
string stackTrac = ex.StackTrace;
//Write this stackTrac to any file where you want
}
Upvotes: 0
Reputation: 11647
Take a look at AppDomain.UnhandledException event. It seems that this is exactly what you need.
Upvotes: 4
Reputation: 62484
I believe you can do this by listening to AppDomain.UnhandledException event. In case of WPF it worth listening to Application.Current.Dispatcher.UnhandledException as well
Upvotes: 0