I would like to record the call stack on an object that gets passed around through some complicated multi-threaded code. Environment.StackTrace gives you that call stack but it's very difficult to read.
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at Foo.Bar.Biz(Monolith monolith) in C:\\Users\\Me\\Google\\Source\\Search.cs :line 70\r\n at Blah.Nonsense.Business(Monolith monolith) in C:\\Users\\Me\\Google\\Source\\Prediction.cs :line 129\r\n at ... you get the point I just need to see the file, class, method, and line. Is there a correct way to get that information? Below is the method that I wrote but it's pretty ugly because of all the string manipulation.
public static List<string[]> GetCallstack() { List<string[]> callstack = new List<string[]>(); string stackTrace = Environment.StackTrace; string[] stackInstances = stackTrace.Split(new string[] { "\r\n" }, StringSplitOptions.None); foreach (string stackInstance in stackInstances) { var stackInstanceComponents = stackInstance.Split(new string[] { ") in ", ":line " }, StringSplitOptions.None); if (stackInstanceComponents.Length == 3) { string classAndMethod = string.Join(".", stackInstanceComponents[0].Split('.').Reverse().Take(2).Reverse().ToArray()) + ")"; string path = string.Join("/", stackInstanceComponents[1].Split(System.IO.Path.DirectorySeparatorChar).Reverse().Take(2).Reverse().ToArray()).Replace("at ", ""); string line = stackInstanceComponents[2]; if (classAndMethod != "Utility.GetCallstack()") { callstack.Add(new string[] { classAndMethod, path, line }); } } } return callstack; }