Search code examples
c#.netloggingstack-traceprintstacktrace

How to print the current Stack Trace in .NET without any exception?


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();
}

Solution

  • 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.