如何将堆栈跟踪转换为字符串?
将 Throwable.getStackTrace() 的结果转换为描述堆栈跟踪的字符串的最简单方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
将 Throwable.getStackTrace() 的结果转换为描述堆栈跟踪的字符串的最简单方法是什么?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(30)
使用
Throwable.printStackTrace(PrintWriter pw)
将堆栈跟踪发送到适当的编写器。Use
Throwable.printStackTrace(PrintWriter pw)
to send the stack trace to an appropriate writer.可以使用以下方法将
Exception
堆栈跟踪转换为String
。 这个类在 Apache commons-lang 中可用,它是最常见的依赖库,具有许多流行的开源代码org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(可抛出)
One can use the following method to convert an
Exception
stack trace toString
. This class is available in Apache commons-lang which is most common dependent library with many popular open sourcesorg.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)
这应该有效:
This should work:
如果您正在为 Android 开发,一个更简单的方法是使用这个:
格式与 getStacktrace 相同,例如
If you are developing for Android, a far easier way is to use this:
The format is the same as getStacktrace, for e.g.
Guava 的
Throwables
类如果您有实际的
Throwable
实例,Google Guava 提供Throwables.getStackTraceAsString()< /代码>
。
示例:
这在幕后使用了
printStackTrace
,因此它输出一个递归的、修剪的堆栈跟踪(即,原因链中多个原因共有的帧仅打印一次) 。Guava's
Throwables
classIf you have the actual
Throwable
instance, Google Guava providesThrowables.getStackTraceAsString()
.Example:
This uses
printStackTrace
under the covers so it outputs a recurisve, trimmed stack trace (i.e., one where frames common to multiple causes in the cause chain are printed only once).警告:不包括原因(这通常是有用的位!)
WARNING: Does not include cause (which is usually the useful bit!)
对我来说,最干净、最简单的方法是:
For me the cleanest and easiest way was:
以下代码允许您以
String
格式获取整个 stackTrace,而无需使用 log4J 甚至java.util.Logger
等 API:The following code allows you to get the entire stackTrace with a
String
format, without using APIs like log4J or evenjava.util.Logger
:将堆栈跟踪打印到
PrintStream
,然后将其转换为String
:Print the stack trace to a
PrintStream
, then convert it to aString
:这是一个可直接复制粘贴到代码中的版本:
或者,在 catch 块中
Here is a version that is copy-pastable directly into code:
Or, in a catch block
是将结果转换为字符串的最简单方法
我在程序中使用它来打印堆栈跟踪
Is the easiest way to convert the result into String
I am using this in my program to print the stack trace
Kotlin >= 1.4
使用内置函数
Throwable
上的stackTraceToString()
。科特林 1.4
扩展 Throwable 类将为您提供 String 属性
error.stackTraceString
:Kotlin >= 1.4
Use the built-in function
stackTraceToString()
on aThrowable
.Kotlin < 1.4
Extending the Throwable class will give you the String property
error.stackTraceString
:如果您使用的是 Java 8,请尝试此操作,
您可以找到
Throwable.java
提供的getStackTrace()
函数的代码为:以及
StackTraceElement
,它提供了toString()
,如下所示:因此只需将
StackTraceElement
与“\n”连接起来即可。if you are using Java 8, try this
you can find the code for
getStackTrace()
function provided byThrowable.java
as :and for
StackTraceElement
, it providestoString()
as follows:So just join the
StackTraceElement
with "\n".将堆栈跟踪打印到字符串
当您想要打印当前线程堆栈跟踪而不创建 Throwable 实例时,它很有用 - 但请注意,创建新的 Throwable 并从那里获取堆栈跟踪实际上比调用 Thread.getStackTrace 更快、更便宜。
Printing stack trace to string
It's useful when you want to print the current thread stack trace without creating instance of
Throwable
- but note that creating newThrowable
and getting stack trace from there is actually faster and cheaper than callingThread.getStackTrace
.来自 Apache Commons Lang 3.4 的代码 (JavaDoc):
与其他答案的区别在于它使用
autoFlushPrintWriter
上的 code>。Code from Apache Commons Lang 3.4 (JavaDoc):
The difference with the other answers is that it uses
autoFlush
on thePrintWriter
.第一组评论中的巧妙狙击非常有趣,但这实际上取决于您想要做什么。
如果您还没有正确的库,那么 3 行代码(如 D. Wroblewski 的答案)是完美的。
OTOH,如果您已经拥有 apache.commons 库(就像大多数大型项目一样),那么 Amar 的答案会更短。
好的,您可能需要十分钟才能获取该库并正确安装它(如果您知道自己在做什么,则不到一分钟)。 但时间在流逝,所以你可能没有多余的时间。
Jarek Przygódzki 有一个有趣的警告——“如果你不需要嵌套异常”。
但是,如果我确实需要完整的堆栈跟踪(嵌套的等等)怎么办? 在这种情况下,秘密是使用 apache.common 的 getFullStackTrace (请参阅 http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/ lang/exception/ExceptionUtils.html#getFullStackTrace%28java.lang.Throwable%29)
它救了我的命。 谢谢阿马尔的提示!
The clever sniping in the first set of comments was very amusing, but it really depends on what you are trying to do.
If you don't already have the correct library, then 3 lines of code (as in D. Wroblewski's answer) is perfect.
OTOH, if you already have the apache.commons library (as most large projects will), then Amar's answer is shorter.
OK, it might take you ten minutes to get the library and install it correctly (less than one if you know what you're doing). But the clock is ticking, so you may not have the time to spare.
Jarek Przygódzki had an interesting caveat--"If you don't need nested exceptions".
But what if I do need the full stack traces, nested and all? In that case, the secret is to use apache.common's getFullStackTrace (see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html#getFullStackTrace%28java.lang.Throwable%29)
It saved my bacon. Thanks, Amar, for the hint!
使用 Java 8 Stream API你可以这样做:
它将获取堆栈跟踪元素数组,将它们转换为字符串并连接成多行字符串。
With Java 8 Stream API you can do something like this:
It will take array of stack trace elements, convert them to string and join into multiline string.
如果没有
java.io.*
,它可以像这样完成。然后
trace
变量保存您的堆栈跟踪。 输出还保存初始原因,输出与printStackTrace()
相同,例如,
printStackTrace()
产生:打印时
trace
字符串保存到标准输出Without
java.io.*
it can be done like this.And then the
trace
variable holds your stack trace. Output also holds the initial cause, the output is identical toprintStackTrace()
Example,
printStackTrace()
yields:The
trace
String holds, when printed tostdout
对 Gala 答案的扩展,其中还包括异常的原因:
an exapansion on Gala's answer that will also include the causes for the exception:
斯卡拉版本
Scala version
如果您不想使用外部库并且不开发 对于 Android,您可以创建一个 '扩展'方法 像这样:
If you don't want to use an external library and you're not developing for Android, you could create an 'extension' method like this:
解决方案是将数组的stackTrace转换为字符串数据类型。 请参见以下示例:
The solution is to convert the stackTrace of array to string data type. See the following example:
我的 oneliner 将堆栈跟踪转换为随附的多行字符串:
轻松“按原样”传递给记录器。
My oneliner to convert stack trace to the enclosed multi-line string:
Easy to pass to the logger "as is".
几个选项
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
使用 Google Guava lib
String stackTrace = Throwables.getStackTraceAsString ( myException ) ;
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)
Few options
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Using Google Guava lib
String stackTrace = Throwables.getStackTraceAsString ( myException ) ;
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)
当您运行该程序时,输出将类似于:
When you run the program, the output will be something similar:
我想知道为什么没有人提到 ExceptionUtils.getStackFrames(exception)
对于我来说,这是转储堆栈跟踪及其所有原因的最方便的方法:
I wonder why no one mentioned
ExceptionUtils.getStackFrames(exception)
For me it's the most convenient way to dump stacktrace with all its causes to the end:
警告:这可能有点偏离主题,但是哦,好吧……;)
我不知道最初的发帖者想要将堆栈跟踪作为字符串的原因是什么。 当堆栈跟踪应该以 SLF4J/Logback LOG 结束,但没有或不应该抛出异常时,我会这样做:
我喜欢它,因为它不需要外部库(除了您的日志记录后端,它将就位)当然,大多数时候都是如此)。
Warning: This may be a bit off topic, but oh well... ;)
I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:
I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).
我不久前为此编写了一些方法,所以我想为什么不为此投入两分钱呢。
示例:
打印:
I wrote a few methods for this a while ago, so I figured why not throw my two cents at this.
Example:
Prints: