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();
}
This question is related to
c#
.net
logging
stack-trace
printstacktrace
An alternative to System.Diagnostics.StackTrace
is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.
Another useful option is to use the $CALLER
and $CALLSTACK
debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.
There are two ways to do this. The System.Diagnostics.StackTrace()
will give you a stack trace for the current thread. If you have a reference to a Thread
instance, you can get the stack trace for that via the overloaded version of StackTrace()
.
You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.
You can also do this in the Visual Studio debugger without modifying the code.
Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.
Console.WriteLine(
new System.Diagnostics.StackTrace().ToString()
);
The output will be similar to:
at YourNamespace.Program.executeMethod(String msg)
at YourNamespace.Program.Main(String[] args)
Replace Console.WriteLine
with your Log
method. Actually, there is
no need for .ToString()
for the Console.WriteLine case as it accepts
object
. But you may need that for your Log(string msg) method.
private void ExceptionTest()
{
try
{
int j = 0;
int i = 5;
i = 1 / j;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
var stList = ex.StackTrace.ToString().Split('\\');
Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
}
}
Seems to work for me
Source: Stackoverflow.com