Problem
Der Umgang mit Bugs, ist ein zentrales Thema in der Softwareentwicklung. Bestenfalls werden diese in einem Testprozess schon erkannt. Können allerdings auch erst vom Kunden erfasst werden. Oftmals steht dem Entwickler nicht viel zu Verfügung um Bugs zu analysieren. Beliebt ist es Logs zu schreiben und Exceptions in Logfiles zu erfassen.
Natürlich ist das Schreiben von ausführlichen Logs Performance intensive und in einer Produktivumgebung nicht gerade gewünscht. Weiterhin ist das Schreiben von guten Logs nicht selbstverständlich, dies soll allerdings nicht Thema diesem Blogeintrag sein.
Ein Beispiel eines Logs wäre der Stacktrace. Dieser wird bei einer Exception ausgelöst und beschreibt die letzten Prozessschritte, falls diese im Stack noch vorhanden sind. In dem Beispiel unten wurde eine Exception in der Methode „test“ aufgegeben. Die jeweilige Datei und dessen Code-Zeile ist auch aufgelistet.
1 2 3 4 | bei System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) bei System.Environment.get_StackTrace() bei ConsoleApp2.Program.test(Int32 wert) in C:\\Users\\lpl\\source\epos\\ConsoleApp2\\ConsoleApp2\\Program.cs:Zeile 31. bei ConsoleApp2.Program.Main(String[] args) in C:\\Users\\lpl\\source\epos\\ConsoleApp2\\ConsoleApp2\\Program.cs:Zeile 16. |
Wie schon zu erkennen sagt der Stacktrace nicht alles aus. Es Ist Z.B nicht klar mit welchen Parametern die Methode „test“ aufgerufen wurde. Auch ist nicht klar welchen stand die lokalen Variablen zum Zeitpunkt der Exception hatten. Ein Stacktrace bietet somit einen Anhaltspunkt, allerdings muss der Entwickler oftmals den Fehler nachstellen um die Ursache zu finden. Und genau dieses Nachstellen verbraucht sehr viel Zeit.
Lösung
Frustriert vom stundenlangen Nachstellen, reifte in mir eine Idee. Was wäre wenn im Stracktrace nicht nur die Aufgerufenen Methoden und Code-Zeilen gelistet würden, sondern auch die Übergabe-Parameter und dessen Werte oder sogar die lokalen Variablen und dessen Werte. Nun ja dann könnte ich sicher 70 % aller Bugs ohne großes Nachstellen lösen können. So utopisch das nun klingt ist es nicht weit Hergeholt. Der eigene Debugger ist in der Lage, genau diese Werte zu ermitteln. Nun bin ich auf eine Lib gestoßen, MdbgEngine. Im Grunde ist diese Lib ein Debugger. Der in der Lage ist genau diese Werte, also Übergabe-Parameter und lokale Variablen auszulesen.
Dieser Debugger müsste allerdings nun so schlank und schnell sein das es keine Performance Einbußen erkennbar sind und dieser sollte nur bei einer Exception reagieren. Die Symboldateien *.pdb müssten zu der Applikation auch bekannt sein. Also fing ich nun an ein kleinen Service zu schreiben, der einen ausgewählten Prozess überwacht und bei einer Exception einmal ein Stacktrace aufbaut und die dazugehörigen Variablen ausließt.
Um den Debugger an einem Prozess anzuhängen sind einmal die ProcessId und einmal der SymbolPath notwendig. Weiterhin gibt es ein Bug-Workaround kurz nach dem Start.
1 2 3 4 5 6 7 8 9 10 11 12 13 | _symbolPath = Uri.UnescapeDataString(symbolPath); _engine=new MDbgEngine(); _engine.Options.SymbolPath = _symbolPath; _process = _engine.Attach(processID); _process.SymbolPath = _symbolPath; _process.Go().WaitOne(); if (!(_process.StopReason is AttachCompleteStopReason)) throw new System.Exception("Unexpected"); _process.Go(); _process.PostDebugEvent += ProcessOnPostDebugEvent; |
Mittels dem PostDebugEvent Event werde ich immer dann informiert, sobald es ein Debugevent gibt. Also auch wenn eine Exception geworfen wird.
In dieser Methode rufe ich eine Prozessmethode auf die, die eigentliche Verarbeitung enthält.
1 2 3 4 5 6 7 8 9 10 11 | private void ProcessOnPostDebugEvent(object sender, CustomPostCallbackEventArgs e) { try { Process(sender, e); } catch (System.Exception) { } } |
In der eigentlichen Verarbeitung gibt es zunächst einen Filter auf den Debugeventtyp. Zusätzlich wird geprüft ob der Exceptionname nicht null ist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | if (e.CallbackType != ManagedCallbackType.OnException2) return; CorException2EventArgs exception; exception = (CorException2EventArgs)e.CallbackArgs; if (exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE || exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE) { MDbgThread thread; thread = _process.Threads.Lookup(exception.Thread); Exception exceptionResult = new Exception(); if (thread.CurrentException.Name != null) { exceptionResult.Name = thread.CurrentException.Name; exceptionResult.Value = thread.CurrentException.Value; } exceptionResult.TypeName = thread.CurrentException.TypeName; |
Das Durchgehen des Stacks und auslesen der Übergabeparameter und der lokalen Variablen wird in einer Schleife durchgeführt. Zu diesem Zeitpunkt wissen wir nur, dass es ein Problem in der Applikation gibt. Um nicht den gesamten Stacktrace zu durchsuchen, habe ich mich auf die letzten 10 Aufrufe beschränkt. Zum Ende der Methode wird das Ergebnis in einer Json-Datei gespeichert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | var maxCount = 10; var count = 0; foreach (var frame in thread.Frames) { if (frame.Function == null) continue; if (count >= maxCount) break; count++; var frameResult = new Frame(); if (frame.SourcePosition != null) { frameResult.Path = frame.SourcePosition.Path; frameResult.Line = frame.SourcePosition.Line; } frameResult.FunctionName = frame.Function.FullName; if (frame.IsManaged && !frame.IsInfoOnly) { try { foreach (var argument in frame.Function.GetArguments(frame)) { var value = GetValue(argument); if (value != null) frameResult.Parameter.Add(value); } } catch (System.Exception) { } try { foreach (var variable in frame.Function.GetActiveLocalVars(frame)) { var value = GetValue(variable); if (value != null) frameResult.LocalVariables.Add(value); } } catch (System.Exception) { } } exceptionResult.Frames.Add(frameResult); } CreateTraceFile(thread.CurrentException.CorValue.Raw.GetHashCode() + "_" + thread.CurrentException.CorValue.Address, exceptionResult); |
Nun stellt sich noch die Frage wie wird, mit komplexen Typen umgegangen. Der Debugger bietet einem die Möglichkeit komplexe typen komplett, das heißt jede interne Variable, auszulisten.
Dies kann ich allerdings nicht empfehlen, es würde nur unnötig Zeit verschwenden und kaum bei der Lösung des Problems beitragen.
Deshalb werden maximal 3 Ebenen Tief eines komplexen Objektes aufgelistet. Da dies nicht gereicht hat, wurden Namespaces von diesem Vorgehen ausgeschlossen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | private Value GetValue(MDbgValue aValue) { try { Value value = new Value(); value.Name = aValue.Name; if (aValue.IsNull) { value.TypeName = aValue.TypeName; value.ValueO = "null"; } else { value.TypeName = aValue.TypeName; value.ValueO = expandValue(aValue); } return value; } catch (System.Exception) { return null; } } private string expandValue(MDbgValue value) { if(value.TypeName.Contains("WebControls") || value.TypeName.Contains("ascx") || value.TypeName.Contains("ASP") || value.TypeName.Contains("System.Web")) return value.GetStringValue(0); int level = 0; string result = ""; while (level <= 3) { try { result = value.GetStringValue(level); level++; } catch (System.Exception) { return result; } } return result; } |
Die ProcessId, den SymbolPath und den Speicherort musste ich mir nur noch über Parameter an mein Service übergaben lassen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | class Options { [Value(0, Required = true, MetaName = "ProcessID", HelpText = "ID off Process")] public int ProcessID { get; set; } [Value(1, Required = true , MetaName = "FilePath", HelpText = @"Path to folder where debug files are saved. HttpRuntime.AppDomainAppPath + \"\\\\App_Data\\\\TraceFiles\\\\\" ")] public string FilePath { get; set; } [Value(2, Required = true, MetaName = "SymbolPath", HelpText = @"Path to folder where dlls and symbols are stored. HttpRuntime.AppDomainAppPath + \"\\\\bin\" ")] public string SymbolPath { get; set; } } static void Main(string[] args) { CommandLine.Parser.Default.ParseArguments <options>(args) .WithParsed <options>(Start);</options></options> AppDomain appDomain = AppDomain.CurrentDomain; appDomain.ProcessExit += new EventHandler(OnClose); while (true) { Thread.Sleep(1000); } } private static void Start(Options obj) { stackTrace = new StackTraceDataCollectorService(obj.ProcessID, obj.FilePath, obj.SymbolPath); } } |
Das Ergebnis sieht nun wie folgt aus.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | { "Name": null, "Value": null, "TypeName": "System.Exception", "Frames": [ { "Path": "source\\\epos\\\\ConsoleApp2\\\\ConsoleApp2\\\\Program.cs", "Line": 35, "FunctionName": "ConsoleApp2.Program.test", "Parameter": [ { "Name": "wert", "TypeName": "N/A", "ValueO": "null" }, { "Name": "wert2", "TypeName": "System.Int32", "ValueO": "2" }, { "Name": "StringValue", "TypeName": "System.String", "ValueO": "\"myvalue\"" } ], "LocalVariables": [ { "Name": "b", "TypeName": "System.Int32", "ValueO": "1" } ] }, { "Path": "source\\\epos\\\\ConsoleApp2\\\\ConsoleApp2\\\\Program.cs", "Line": 17, "FunctionName": "ConsoleApp2.Program.Main", "Parameter": [ { "Name": "args", "TypeName": "N/A", "ValueO": "null" } ], "LocalVariables": [] } ], "DateTime": "2019-10-29T09:41:18.8572539+01:00" } |
Weiter unten finden Sie die Sourcen.
Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using Microsoft.Samples.Debugging.CorDebug; using Microsoft.Samples.Debugging.CorDebug.NativeApi; using Microsoft.Samples.Debugging.MdbgEngine; using CommandLine; namespace StackTraceApp { class Program { private static StackTrace stackTrace class Options { [Value(0, Required = true, MetaName = "ProcessID", HelpText = "ID off Process")] public int ProcessID { get; set; } [Value(1, Required = true , MetaName = "FilePath", HelpText = @"Path to folder where debug files are saved. HttpRuntime.AppDomainAppPath + \"\\\\App_Data\\\\TraceFiles\\\\\" ")] public string FilePath { get; set; } [Value(2, Required = true, MetaName = "SymbolPath", HelpText = @"Path to folder where dlls and symbols are stored. HttpRuntime.AppDomainAppPath + \"\\\\bin\" ")] public string SymbolPath { get; set; } } static void Main(string[] args) { CommandLine.Parser.Default.ParseArguments <options>(args) .WithParsed <options>(Start);</options></options> AppDomain appDomain = AppDomain.CurrentDomain; appDomain.ProcessExit += new EventHandler(OnClose); while (true) { Thread.Sleep(1000); } } private static void OnClose(object sender, EventArgs e) { stackTrace.Close(); } private static void Start(Options obj) { stackTrace = new StackTraceDataCollectorService(obj.ProcessID, obj.FilePath, obj.SymbolPath); } } } |
StackTraceService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Web; using Microsoft.Samples.Debugging.CorDebug; using Microsoft.Samples.Debugging.CorDebug.NativeApi; using Microsoft.Samples.Debugging.MdbgEngine; using Newtonsoft.Json; namespace StackTraceApp { public class StackTraceService { private MDbgEngine _engine; private MDbgProcess _process; private string _filePath; private string _symbolPath; public StackTraceService(int processID, string filePath, string symbolPath) { _filePath = Uri.UnescapeDataString(filePath); _symbolPath = Uri.UnescapeDataString(symbolPath); _engine = new MDbgEngine(); _engine.Options.SymbolPath = _symbolPath; _process = _engine.Attach(processID); _process.SymbolPath = _symbolPath; _process.Go().WaitOne(); if (!(_process.StopReason is AttachCompleteStopReason)) throw new System.Exception("Unexpected"); _process.Go(); _process.PostDebugEvent += ProcessOnPostDebugEvent; System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(CleanUp); aTimer.Interval = 60000; aTimer.Enabled = true; aTimer.AutoReset = true; AllCleanUp(); } public void Close() { _process.Detach(); } private void AllCleanUp() { if (!Directory.Exists(_filePath)) { Directory.CreateDirectory(_filePath); } System.IO.DirectoryInfo di = new DirectoryInfo(_filePath); foreach(FileInfo file in di.GetFiles()) { file.Delete(); } } private void CleanUp(object sender, ElapsedEventArgs e) { if (!Directory.Exists(_filePath)) { Directory.CreateDirectory(_filePath); } System.IO.DirectoryInfo di = new DirectoryInfo(_filePath); foreach(FileInfo file in di.GetFiles()) { if (file.CreationTime.AddMinutes(30) & lt; = DateTime.Now) { file.Delete(); } } } private void ProcessOnPostDebugEvent(object sender, CustomPostCallbackEventArgs e) { try { Process(sender, e); } catch (System.Exception) {} } private void Process(object sender, CustomPostCallbackEventArgs e) { if (e.CallbackType != ManagedCallbackType.OnException2) return; CorException2EventArgs exception; exception = (CorException2EventArgs) e.CallbackArgs; if (exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE || exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE) { MDbgThread thread; thread = _process.Threads.Lookup(exception.Thread); Exception exceptionResult = new Exception(); if (thread.CurrentException.Name != null) { exceptionResult.Name = thread.CurrentException.Name; exceptionResult.Value = thread.CurrentException.Value; } exceptionResult.TypeName = thread.CurrentException.TypeName; var maxCount = 10; var count = 0; bool wasSPData = false; foreach(var frame in thread.Frames) { if (frame.Function == null) continue; if (!wasSPData & amp; & amp; frame.Function.FullName.Contains("SPData")) { wasSPData = true; maxCount = count + 3; } if (count & gt; = maxCount) break; count++; var frameResult = new Frame(); if (frame.SourcePosition != null) { frameResult.Path = frame.SourcePosition.Path; frameResult.Line = frame.SourcePosition.Line; } frameResult.FunctionName = frame.Function.FullName; if (frame.IsManaged & amp; & amp; !frame.IsInfoOnly) { try { foreach(var argument in frame.Function.GetArguments(frame)) { var value = GetValue(argument); if (value != null) frameResult.Parameter.Add(value); } } catch (System.Exception) { } try { foreach(var variable in frame.Function.GetActiveLocalVars(frame)) { var value = GetValue(variable); if (value != null) frameResult.LocalVariables.Add(value); } } catch (System.Exception) { } } exceptionResult.Frames.Add(frameResult); } CreateTraceFile(thread.CurrentException.CorValue.Raw.GetHashCode() + "_" + thread.CurrentException.CorValue.Address, exceptionResult); } } private struct ToPrint { public MDbgThread Thread; public Exception ExceptionResult; } private Value GetValue(MDbgValue aValue) { try { Value value = new Value(); value.Name = aValue.Name; if (aValue.IsNull) { value.TypeName = aValue.TypeName; value.ValueO = "null"; } else { value.TypeName = aValue.TypeName; value.ValueO = expandValue(aValue); } return value; } catch (System.Exception) { return null; } } private string expandValue(MDbgValue value) { if (value.TypeName.Contains("WebControls") || value.TypeName.Contains("ascx") || value.TypeName.Contains("ASP") || value.TypeName.Contains("System.Web")) return value.GetStringValue(0); int level = 0; string result = ""; while (level & lt; = 3) { try { result = value.GetStringValue(level); level++; } catch (System.Exception) { return result; } } return result; } private void CreateTraceFile(string ID, Exception exceptionResult) { if (!Directory.Exists(_filePath)) { Directory.CreateDirectory(_filePath); } string path = Path.Combine(_filePath, ID.ToString()); if (File.Exists(path)) { File.Delete(path); } byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(exceptionResult)); FileStream fs = File.Create(path); fs.Write(bytes, 0, bytes.Length); fs.Close(); } private class Exception { public string Name { get; set; } public Object Value { get; set; } public string TypeName { get; set; } public List Frames { get; set; } = new List(); public DateTime DateTime { get; set; } = DateTime.Now; } private class Frame { public string Path { get; set; } public int Line { get; set; } public string FunctionName { get; set; } public List < value > Parameter { get; set; } = new List < value > (); < /value></value > public List < value > LocalVariables { get; set; } = new List < value > (); } < /value></value > private class Value { public string Name { get; set; } public string TypeName { get; set; } public Object ValueO { get; set; } } } } |