Sunday, March 30, 2008

Sample of StackTrace usage.

       Sometimes we want to store in log file error (warning or trace) message and stack trace, from where the message is stored. To solve the problem it is suggested to use class StackTrace.

public class StackTraceSampleClass
{
const string LOG_FILE_NAME = "stackTraceSample.log";
public void Execute()
{
File.Delete(LOG_FILE_NAME);
F1(-10);
F2(-10);
}
void F1(int arg)
{
F(arg);
}
void F2(int arg)
{
F(arg);
}
double F(int arg)
{
if (arg < 0)
{
StackTrace stackTrace = new StackTrace(true);
string logContent = String.Format("unexpected value of arg: {0}, stack: {1}", arg, stackTrace);
File.AppendAllText(LOG_FILE_NAME, logContent);
return 0;
}
return Math.Sqrt(arg);
}
}
File stackTraceSample.log in Debug mode:


stackTraceInDebugMode 


File stackTraceSample.log in Release mode:


stackTraceInReleaseMode 


Reference:



StackTrace Class



Sample of C# Trace.Fail() method.

No comments: