Print stack trace information from C#

前端 未结 5 1356
旧时难觅i
旧时难觅i 2020-12-04 10:27

As part of some error handling in our product, we\'d like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the e

相关标签:
5条回答
  • 2020-12-04 10:39

    You should be able to get a StackTrace object instead of a string by saying

    var trace = new System.Diagnostics.StackTrace(exception);
    

    You can then look at the frames yourself without relying on the framework's formatting.

    See also: StackTrace reference

    0 讨论(0)
  • 2020-12-04 10:47

    Just to make this a 15 sec copy-paste answer:

    static public string StackTraceToString()
    {
        StringBuilder sb = new StringBuilder(256);
        var frames = new System.Diagnostics.StackTrace().GetFrames();
        for (int i = 1; i < frames.Length; i++) /* Ignore current StackTraceToString method...*/
        {
            var currFrame = frames[i];
            var method = currFrame.GetMethod();
            sb.AppendLine(string.Format("{0}:{1}",                    
                method.ReflectedType != null ? method.ReflectedType.Name : string.Empty,
                method.Name));
        }
        return sb.ToString();
    }
    

    (based on Lindholm answer)

    0 讨论(0)
  • 2020-12-04 10:49

    Or there is even shorter version..

    Console.Write(exception.StackTrace);
    
    0 讨论(0)
  • 2020-12-04 10:59

    Here is the code I use to do this without an exception

    public static void LogStack()
    {
      var trace = new System.Diagnostics.StackTrace();
      foreach (var frame in trace.GetFrames())
      {
        var method = frame.GetMethod();
        if (method.Name.Equals("LogStack")) continue;
        Log.Debug(string.Format("{0}::{1}", 
            method.ReflectedType != null ? method.ReflectedType.Name : string.Empty,
            method.Name));
      }
    }
    
    0 讨论(0)
  • 2020-12-04 11:00

    As alternative, log4net, though potentially dangerous, has given me better results than System.Diagnostics. Basically in log4net, you have a method for the various log levels, each with an Exception parameter. So, when you pass the second exception, it will print the stack trace to whichever appender you have configured.

    example: Logger.Error("Danger!!!", myException );

    The output, depending on configuration, looks something like

    System.ApplicationException: Something went wrong.
       at Adapter.WriteToFile(OleDbCommand cmd) in C:\Adapter.vb:line 35
       at Adapter.GetDistributionDocument(Int32 id) in C:\Adapter.vb:line 181
       ...
    
    0 讨论(0)
提交回复
热议问题