简体   繁体   中英

C# Portable Class Library Equivalent of System.Diagnostics.StackTrace

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 ac# 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.

Try to use the Environment.StackTrace property .

The StackTrace property lists method calls in reverse chronological order, that is, the most recent method call is described first, and one line of stack trace information is listed for each method call on the stack. However, the StackTrace property might not report as many method calls as expected due to code transformations that occur during optimization.

EDIT:

Version description seems to be stating that Environment class is supported by PCL :

Version Information .NET Framework Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client Profile Supported in: 4, 3.5 SP1 Portable Class Library Supported in: Portable Class Library .NET for Windows Store apps Supported in: Windows 8 Supported in: Windows Phone 8.1 Supported in: Windows Phone Silverlight 8.1 Supported in: Windows Phone Silverlight 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM