Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a stack trace in .NET in normal execution?

In VB .NET, I know I can get a stack trace by looking at the value of ex.StackTrace when handling an exception. How can I get the functions on the stack when I am not handling an exception? I am looking to implement a logging system of some sort to record the steps the user takes prior to a crash to assist in debugging.

like image 234
davidscolgan Avatar asked Jul 15 '10 19:07

davidscolgan


People also ask

How do I get a stack trace?

We can obtain a stack trace from a thread by calling the getStackTrace() method on the Thread instance. It returns an array of StackTraceElement, from which details about stack frames of the thread can be found.

How do I get full stack trace in Visual Studio?

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, select and hold (or double click) the first column of the row.

How do I get stack trace on Windows?

Each thread has its own call stack, representing the calls made in that thread. To get a stack trace, use the methods GetStackTrace and GetContextStackTrace. A stack trace can be printed using OutputStackTrace and OutputContextStackTrace.

How do I print a full stack trace?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.


2 Answers

Environment.StackTrace

like image 97
MikeD Avatar answered Nov 15 '22 22:11

MikeD


Environment.StackTrace gives you a string, but for more detailed information and options, use the StackTrace class.

To be more specific, check out the constructor options:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.stacktrace.aspx

If you need the stack trace starting at the caller's frame (e.g. in a logging function: you don't want everything to start with MyLogMethod), you should try this one, which takes an int parameter, the number of frames to skip.

http://msdn.microsoft.com/en-us/library/wybch8k4.aspx

If you need the stack trace without source information (e.g. if you don't want to give away information about your source code), try this one:

http://msdn.microsoft.com/en-us/library/6zh7csxz.aspx

Hope that helps!

like image 31
Kieren Johnstone Avatar answered Nov 15 '22 22:11

Kieren Johnstone