开发者

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 as开发者_StackOverflow中文版sembly information from StackTrace object I create from Exception? I'm interested only in chunk of frames inside of whole trace.

Thank you.

Denis.


One way would be to create a StackTrace object, get the frames from it and loop through them, checking whether each frame was created for a method in one of your assemblies.

I don't think you really should do this though. You chould rather focus on getting less error messages in your logs than shortening them (which will likely make things more difficult to debug).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜