IdleBrain wrote:
Thanks for your reply Glenn.
Sorry for my ignorance, but by walking back up the stack frame, do you
mean selecting a different stack frame, which I already did?? I looked
at other frames and unfortunately none of the frames point out to the
line that generated the exception.
The build is currently set to debug... And are you saying that setting
the build to release wouldn't give any line numbers? My whole
intention of trying to log the line numbers is to get a better
understanding of which line in the code generated an exception. Am I
missing anything?
Is there a better way of tracking exceptions other than by logging
method name and stack trace?
Here's some code in a logger module I wrote years ago:
static MethodBase GetCaller()
{
// Get our own, current namespace name.
string namespaceName = new StackFrame(0).GetMethod()
.DeclaringType.ToString();
// We’ll use this to walk the stack looking for a
// method name that is not the same as our method
// name—that is, the name of the method that called
// this method name.
StackTrace trace = new StackTrace(true);
// Look for the first occurence of a stack frame that
// contains a namespace name that is different from our
// own.
string callerNamespace = null;
int i;
MethodBase callerFrame = null;
for (i=0; i<trace.FrameCount; i++)
{
StackFrame frame = trace.GetFrame(i);
callerFrame = frame.GetMethod();
if (callerFrame.DeclaringType.ToString() !=
namespaceName)
{
callerNamespace = callerFrame.DeclaringType
.ToString();
//callerName = callerFrame.Name;
break;
}
}
return callerFrame;
}
In this implementation, GetCaller returns the first method on the stack
that has a namespace different than the one that GetCaller is in (the
idea being that GetCaller lives in a utility library with a namespace
that is different than your application code's namespace). This should
get you on the right track.
You're not missing anything with the line numbers. Well, you'll be
missing them in a release build. That's just how it works. The stack
trace can't give you line numbers if they aren't there, and they are
only there when you do a debug build. But a stack trace of the error is
sure better than nothing.
Instead of trying to recreate the wheel here, you could just use
something like log4net for your logging and just send the stack trace to
it. There's probably not much point in you just trying to find the line
number yourself in the case of a debug build; just send the entire stack
trace output to your logging mechanism.
HTH.
--
-glenn-