How do I log an exception with a full call stack?
I want to use ELMAH to log an exception (without throwing it all the way up the call stack) and it log the entire call stack.
Example code:
protected void Page_Load(object sender, EventArgs e)
{
DoSomething();
}
private void DoSomething()
{
try { TrySomething(); }
catch (Exception ex) { LogException(ex); }
}
private void TrySomething()
{
throw new NotImplementedException();
}
public static void LogExceptio开发者_StackOverflow社区n(Exception ex)
{
var currentStack = new System.Diagnostics.StackTrace(true);
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
Now, within the LogException method I can see the call stack telling me DoSomething() called TrySomething(), and that threw the exception, but I can't see the call stack showing me Page_Load() called DoSomething(). I want to be able to see the full calling stack.
Example of what ex.StackTrace looks like inside LogException method:
at WebApplication1._Default.TrySomething() in C:\Projects\test\GeneralTests\WebApplication1\Default.aspx.cs:line 26
at WebApplication1._Default.DoSomething() in C:\Projects\test\GeneralTests\WebApplication1\Default.aspx.cs:line 20
I can get the full call stack from System.Diagnostics.StackTrace(), for example:
at WebApplication1._Default.LogException(Exception ex)
at WebApplication1._Default.DoSomething()
at WebApplication1._Default.Page_Load(Object sender, EventArgs e)
[snip]
(and I can get line numbers and source file details by walking each frame of StackTrace)
But how do I inject this into the Exception or raise a new Exception with this call stack detail? Is there an elegant way to do this? Have I missed something really obvious?!
You can do something like this to get the full stack when an error ocurrs:
var currentStack = new System.Diagnostics.StackTrace(true);
return currentStack.ToString();
When the app is compiled without debug flags, the stack is not necessarily preserved in execution. You can only guarantee each item being recorded by adding try / catch to every method.
Have you looked at the results of Exception.ToString()? It includes a stack trace. Does it include the kind that you're looking for?
精彩评论