'StackTrace: how to show only my code?

For debugging purposes I store exception's stack trace to log file in my ASP.NET application. But in most of cases it contains a looot of redundant information: stack trace of ASP.NET's core before my routines and System calls after.

Is there any way to trim this unrelevant, not in my assembly information from StackTrace object I create from Exception? I'm interested only in chunk of frames inside of whole trace.

Thank you.

Denis.



Solution 1:[1]

I ended up parsing ex.ToString() and removing unwanted entries with Regex. It's not a universal solution, you have to specify each excluded entry manually, but it helps reduce size of logs and improve log readability. It's also fairly maintainable. Something like this:

private static string TrimStackTrace(Exception ex)
{
    var sb = new StringBuilder();
    string[] lines = ex.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
    var excludeRegex = new Regex(@"^\s+at (Microsoft.AspNetCore|lambda_)");
    foreach (string line in lines)
    {
        if (excludeRegex.IsMatch(line))
        {
            continue;
        }

        sb.AppendLine(line);
    }

    return sb.ToString();
}

You can of course make excluded entries part of your app config.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Zakharov