Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 LogException(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?!

like image 634
Alex Avatar asked Feb 26 '23 02:02

Alex


1 Answers

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();
like image 96
KingOfHypocrites Avatar answered Mar 11 '23 23:03

KingOfHypocrites