C# – How to print the current Stack Trace in .NET without any exception

cloggingnetprintstacktracestack-trace

I have a regular C# code. I have no exceptions. I want to programmatically log the current stack trace for debugging purpose. Example:

public void executeMethod() 
{
    logStackTrace();
    method();
}

Best Answer

Have a look at the System.Diagnostics namespace. Lots of goodies in there!

System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();

This is really good to have a poke around in to learn what's going on under the hood.

I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some. Good luck mate!