我如何在 Java 中将堆栈跟踪添加到我的调试打印输出中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54882/
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
How do I in java add a stacktrace to my debugging printout
提问by Johan Lübcke
What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.
从调试打印输出打印堆栈跟踪的最简单方法是什么?通常在测试期间,您想知道导致引发调试消息的情况的调用堆栈。
采纳答案by Dan Dyer
回答by shsteimer
If you're using log4j
如果您使用的是 log4j
Exception e = new Exception();
log.error("error here", e);
will print the stacktrace to your log.
将堆栈跟踪打印到您的日志。
回答by Dan Dyer
If you want to save the stack trace into a String you can do this;
如果你想将堆栈跟踪保存到一个字符串中,你可以这样做;
String exception = "";
for (StackTraceElement element : e.getStackTrace())
exception += element.toString() + "\n";
Where e is, obviously, an exception.
显然,e 是一个例外。
Besides, it sounds very weird to autogenerate an own Exception just to find get a stack trace for a debug. Get Eclipse and use it's debug mode, it's really awesome.
此外,为了找到调试的堆栈跟踪而自动生成自己的异常听起来很奇怪。拿到 Eclipse 并使用它的调试模式,它真的很棒。
回答by Johan Lübcke
Just creating an arbitrary exception does the trick for me:
只是创建一个任意的异常对我来说就可以了:
System.out.println("Oops, the bad thing happened");
new IllegalStateException().printStackTrace();
回答by Paul Tomblin
As well as what @jjnguy said, if you don't have an exception, you can also call Thread.getStackTrace().
和@jjnguy 说的一样,如果没有异常,也可以调用Thread.getStackTrace()。
回答by jjnguy
You should be catching the exception in a try-catch block.
您应该在 try-catch 块中捕获异常。
e.getStackTrace();
That returns StackTraceElement[] that you can then interpret.
这将返回 StackTraceElement[],然后您可以对其进行解释。
Also:
还:
e.printStackTrace()
will...print the stacktrace.
将...打印堆栈跟踪。
回答by minipif
To simply print the current stack trace to stderr, you can call:
要简单地将当前堆栈跟踪打印到 stderr,您可以调用:
Thread.dumpStack();
which itself just calls:
它本身只是调用:
new Exception("Stack trace").printStackTrace();
To output to stdoutrather than stderr, pass System.outto printStackTrace():
要输出到stdout而不是 stderr,请传递System.out到printStackTrace():
new Exception("Stack trace").printStackTrace(System.out);
回答by sleske
Just because I needed it myself:
只是因为我自己需要它:
As inspired by answer How do I find the caller of a method using stacktrace or reflection?, you can retrieve the call stack using
受到答案的启发我如何使用堆栈跟踪或反射找到方法的调用者?,您可以使用检索调用堆栈
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
Then you process and print/log whatever you are interested in. More work than using Thread.dumpStack(), but more flexible.
然后您可以处理和打印/记录您感兴趣的任何内容。比使用 做更多的工作Thread.dumpStack(),但更灵活。

