Reputation: 1114
A program I am working on has a logging function appropriately named "Error," to notify of errors without crashing the program, however, I would like to include a stack trace so these non-fatal errors can be more easily debugged. My first instinct was to use System.Diagnostics.StackTrace
, which is unfortunately not available in PCL's.
Then, I tried to throw and promptly catch an exception.
try { throw new Exception(); }
catch (Exception ex) { return ex.StackTrace; }
Unfortunately, this only provides the top of the call stack: as it does not unravel the stack on its way down, it doesn't provide any useful information. So, my question is this: How do I get a stack trace in a c# PCL function without throwing an error and catching it at the bottom of the stack? I would prefer to keep the code entirely in the PCL and avoid using abstractions and platform specific implementation code for something so trivial.
Edit as a response to a comment: `throw new Exception(ex) Only adds another layer to the stack trace, so it has two lines in the stack trace function but still fails to retrieve the full trace.
Upvotes: 13
Views: 1994
Reputation: 614
A modern answer for this question is to target .NET Standard, if possible. System.Diagnostics.StackTrace
is available from .NET Standard 2.0.
You can read about Converting Portable Class Libraries to .NET Standard Class Libraries on Microsoft Developer Blogs.
Upvotes: 0