C# 如何在 .NET 中毫无例外地打印当前的 Stack Trace?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/531695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:02:47  来源:igfitidea点击:

How to print the current Stack Trace in .NET without any exception?

c#.netloggingstack-traceprintstacktrace

提问by Ricibald

I have a regular C# code. I have no exceptions. I want to programmatically log the current stack trace for debugging purpose. Example:

我有一个普通的 C# 代码。我没有例外。我想以编程方式记录当前堆栈跟踪以进行调试。例子:

public void executeMethod() 
{
    logStackTrace();
    method();
}

采纳答案by Spence

Have a look at the System.Diagnosticsnamespace. Lots of goodies in there!

看看System.Diagnostics命名空间。里面有很多好吃的!

System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();

This is really good to have a poke around in to learn whats going on under the hood.

深入了解一下幕后发生的事情真是太好了。

I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some. Good luck mate!

我建议您查看日志记录解决方案(例如 NLog、log4net 或 Microsoft 模式和实践企业库),它们可能会实现您的目的,然后是一些。祝你好运!

回答by Brian Rasmussen

There are two ways to do this. The System.Diagnostics.StackTrace()will give you a stack trace for the current thread. If you have a reference to a Threadinstance, you can get the stack trace for that via the overloaded version of StackTrace().

有两种方法可以做到这一点。该System.Diagnostics.StackTrace()会给你当前线程的堆栈跟踪。如果你有一个Thread实例的引用,你可以通过重载的StackTrace().

You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.

您可能还想查看堆栈溢出问题如何获取非当前线程的堆栈跟踪?.

回答by larsmoa

An alternative to System.Diagnostics.StackTraceis to use System.Environment.StackTracewhich returns a string-representation of the stacktrace.

另一种方法System.Diagnostics.StackTrace是使用System.Environment.StackTrace,它返回堆栈跟踪的字符串表示形式。

Another useful option is to use the $CALLERand $CALLSTACKdebugging variables in Visual Studiosince this can be enabled run-time without rebuilding the application.

另一个有用的选项是在 Visual Studio 中使用$CALLER$CALLSTACK调试变量,因为这可以在运行时启用而无需重新构建应用程序。

回答by Hank Schultz

You can also do this in the Visual Studio debugger without modifying the code.

您也可以在 Visual Studio 调试器中执行此操作,而无需修改代码。

  1. Create a breakpoint where you want to see the stack trace.
  2. Right-click the breakpoint and select "Actions..." in VS2015. In VS2010, select "When Hit...", then enable "Print a message".
  3. Make sure "Continue execution" is selected.
  4. Type in some text you would like to print out.
  5. Add $CALLSTACK wherever you want to see the stack trace.
  6. Run the program in the debugger.
  1. 在要查看堆栈跟踪的位置创建一个断点。
  2. 在 VS2015 中右键单击断点并选择“Actions...”。在 VS2010 中,选择“When Hit...”,然后启用“Print a message”。
  3. 确保选择了“继续执行”。
  4. 输入一些您要打印的文本。
  5. 在您想要查看堆栈跟踪的任何位置添加 $CALLSTACK。
  6. 在调试器中运行程序。

Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.

当然,如果您在不同的机器上运行代码,这无济于事,但是能够在不影响发布代码甚至不需要重新启动程序的情况下自动吐出堆栈跟踪会非常方便。

回答by Jeff Jacobs

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

似乎对我有用

回答by epox

Console.WriteLine(
    new System.Diagnostics.StackTrace().ToString()
    );

The output will be similar to:

输出将类似于:

at YourNamespace.Program.executeMethod(String msg)

at YourNamespace.Program.Main(String[] args)

在 YourNamespace.Program.executeMethod(String msg)

在 YourNamespace.Program.Main(String[] args)

Replace Console.WriteLinewith your Logmethod. Actually, there is no need for .ToString()for the Console.WriteLine case as it accepts object. But you may need that for your Log(string msg) method.

替换Console.WriteLine为您的Log方法。实际上,不需要.ToString()Console.WriteLine 案例,因为它接受 object. 但是您的 Log(string msg) 方法可能需要它。