从C#打印堆栈跟踪信息

ang*_*son 51 c# error-handling parsing stack-trace

作为我们产品中某些错误处理的一部分,我们想要转储一些堆栈跟踪信息.但是,我们遇到许多用户只需截取错误消息对话框的屏幕截图,而不是向我们发送程序中可用的完整报告的副本,因此我想在此对话框中提供一些最小的堆栈跟踪信息.

我机器上的.NET堆栈跟踪如下所示:

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
Run Code Online (Sandbox Code Playgroud)

我有这个问题:

格式看起来是这样的:

at <class/method> [in file:line ##]
Run Code Online (Sandbox Code Playgroud)

但是,atin关键字,我认为如果它们运行,比如挪威的.NET运行时而不是我安装的英文版,它们将被本地化.

有没有办法让我以语言中立的方式分离这个堆栈跟踪,这样我才能显示那些有这个条目的文件和行号?

换句话说,我想从上面的文字中获得这些信息:

C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
Run Code Online (Sandbox Code Playgroud)

您提供的任何建议都会有所帮助.

Cur*_*her 71

您应该能够通过说明获取StackTrace对象而不是字符串

var trace = new System.Diagnostics.StackTrace(exception);
Run Code Online (Sandbox Code Playgroud)

然后,您可以自己查看框架,而无需依赖框架的格式.

另请参见:StackTrace参考


小智 28

这是我用来执行此操作的代码,没有例外

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));
  }
}
Run Code Online (Sandbox Code Playgroud)


Her*_*ess 18

只需要15秒复制粘贴答案:

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();
}
Run Code Online (Sandbox Code Playgroud)

(根据Lindholm的回答)

  • 感谢那.请注意,您可以使用sb.AppendLine(...)来避免硬编码特定的行尾字符. (3认同)

Aft*_*ock 8

或者甚至更短的版本..

Console.Write(exception.StackTrace);
Run Code Online (Sandbox Code Playgroud)