将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?
使用Throwable.printStackTrace(PrintWriter pw)将堆栈跟踪发送到适当的编写器。
import java.io.StringWriter;
import java.io.PrintWriter;
// ...
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String sStackTrace = sw.toString(); // stack trace as a string
System.out.println(sStackTrace);
警告:不包括原因(通常是有用的位!)
public String stackTraceToString(Throwable e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace()) {
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
这应该是有效的:
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
可以使用以下方法将异常堆栈跟踪转换为字符串。该类在Apache commons-lang中可用,这是许多流行开源中最常见的依赖库
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(可丢弃)
将堆栈跟踪打印到字符串
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceUtils {
public static String stackTraceToString(StackTraceElement[] stackTrace) {
StringWriter sw = new StringWriter();
printStackTrace(stackTrace, new PrintWriter(sw));
return sw.toString();
}
public static void printStackTrace(StackTraceElement[] stackTrace, PrintWriter pw) {
for(StackTraceElement stackTraceEl : stackTrace) {
pw.println(stackTraceEl);
}
}
}
当您想要打印当前线程堆栈跟踪而不创建Throwable实例时,这非常有用,但请注意,创建新的Throwable并从中获取堆栈跟踪实际上比调用thread.getStackTrace更快、更便宜。
番石榴的丢弃类
如果您有实际的Throwables实例,GoogleGuava提供Throwables.getStackTraceAsString()。
例子:
String s = Throwables.getStackTraceAsString ( myException ) ;
如果你是为Android开发的,一个更简单的方法是使用这个:
import android.util.Log;
String stackTrace = Log.getStackTraceString(exception);
格式与getStacktrace相同,例如。
09-24 16:09:07.042:I/System.out(4844):java.lang.NullPointerException09-24 16:09:07.042:I/System.out(4844):在com.temp.ttscancel.MainActivity.onCreate(MainActivity.java:43)09-24 16:09:07.042:I/System.out(4844):在android.app.Activity.performCreate(Activity.java:5248)09-24 16:09:07.043:I/System.out(4844):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.access$800(ActivityThread.java:139)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)09-24 16:09:07.043:I/System.out(4844):在android.os.Handler.dispatchMessage(Handler.java:102)09-24 16:09:07.043:I/System.out(4844):在android.os.Looper.lop(Looper.java:136)09-24 16:09:07.044:I/System.out(4844):在android.app.ActivityThread.main(ActivityThread.java:5097)09-24 16:09:07.044:I/System.out(4844):在java.lang.reflect.Method.invokeNative(本机方法)09-24 16:09:07.044:I/System.out(4844):在java.lang.reflect.Method.invoke(Method.java:515)09-24 16:09:07.044:I/System.out(4844):在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)09-24 16:09:07.044:I/System.out(4844):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
下面是一个可以直接复制到代码中的版本:
import java.io.StringWriter;
import java.io.PrintWriter;
//Two lines of code to get the exception into a StringWriter
StringWriter sw = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(sw));
//And to actually print it
logger.info("Current stack trace is:\n" + sw.toString());
或者,在捕捉块中
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
logger.info("Current stack trace is:\n" + sw.toString());
}
以下代码允许您使用字符串格式获取整个stackTrace,而无需使用log4J或java.util.Logger等API:
catch (Exception e) {
StackTraceElement[] stack = e.getStackTrace();
String exception = "";
for (StackTraceElement s : stack) {
exception = exception + s.toString() + "\n\t\t";
}
System.out.println(exception);
// then you can send the exception string to a external file.
}
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
第一组评论中巧妙的狙击非常有趣,但这真的取决于你想做什么。如果您还没有正确的库,那么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)
这救了我的命。谢谢阿玛的提示!
如果你不想使用外部库,而且你不是为Android开发的,你可以创建这样的“扩展”方法:
public static String getStackTraceString(Throwable e) {
return getStackTraceString(e, "");
}
private static String getStackTraceString(Throwable e, String indent) {
StringBuilder sb = new StringBuilder();
sb.append(e.toString());
sb.append("\n");
StackTraceElement[] stack = e.getStackTrace();
if (stack != null) {
for (StackTraceElement stackTraceElement : stack) {
sb.append(indent);
sb.append("\tat ");
sb.append(stackTraceElement.toString());
sb.append("\n");
}
}
Throwable[] suppressedExceptions = e.getSuppressed();
// Print suppressed exceptions indented one level deeper.
if (suppressedExceptions != null) {
for (Throwable throwable : suppressedExceptions) {
sb.append(indent);
sb.append("\tSuppressed: ");
sb.append(getStackTraceString(throwable, indent + "\t"));
}
}
Throwable cause = e.getCause();
if (cause != null) {
sb.append(indent);
sb.append("Caused by: ");
sb.append(getStackTraceString(cause, indent));
}
return sb.toString();
}
Apache Commons Lang 3.4(JavaDoc)代码:
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
与其他答案的不同之处在于,它在PrintWriter上使用autoFlush。
没有java.io.*,它可以这样做。
String trace = e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
然后跟踪变量保存堆栈跟踪。输出也包含初始原因,输出与printStackTrace()相同
例如,printStackTrace()产生:
java.io.FileNotFoundException: / (Is a directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:9)
当打印到stdout时,跟踪字符串保持
java.io.FileNotFoundException: / (Is a directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:9)
对Gala的回答进行了详细分析,其中还将包括例外情况的原因:
private String extrapolateStackTrace(Exception ex) {
Throwable e = ex;
String trace = e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
while (e.getCause() != null) {
e = e.getCause();
trace += "Cause by: " + e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
}
return trace;
}
Kotlin>=1.4
在Throwable上使用内置函数stackTraceToString()。
Kotlin<1.4
扩展Throwable类将提供String属性error.stackTraceString:
val Throwable.stackTraceString: String
get() {
val sw = StringWriter()
val pw = PrintWriter(sw)
this.printStackTrace(pw)
return sw.toString()
}
private String getCurrentStackTraceString() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return Arrays.stream(stackTrace).map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
}
老问题,但我想补充一个特殊情况,即您不想打印所有堆栈,通过删除一些您实际上不感兴趣的部分,排除某些类或包。
使用SelectivePrintWriter代替PrintWriter:
// This filters out this package and up.
String packageNameToFilter = "org.springframework";
StringWriter sw = new StringWriter();
PrintWriter pw = new SelectivePrintWriter(sw, packageNameToFilter);
e.printStackTrace(pw);
String sStackTrace = sw.toString();
System.out.println(sStackTrace);
其中SelectivePrintWriter类由以下给出:
public class SelectivePrintWriter extends PrintWriter {
private boolean on = true;
private static final String AT = "\tat";
private String internal;
public SelectivePrintWriter(Writer out, String packageOrClassName) {
super(out);
internal = "\tat " + packageOrClassName;
}
public void println(Object obj) {
if (obj instanceof String) {
String txt = (String) obj;
if (!txt.startsWith(AT)) on = true;
else if (txt.startsWith(internal)) on = false;
if (on) super.println(txt);
} else {
super.println(obj);
}
}
}
请注意,这个类可能很容易被Regex、contains或其他条件过滤掉。还要注意,这取决于可丢弃的实现细节(不太可能改变,但仍然如此)。
警告:这可能有点离题,但哦,好吧…;)
我不知道最初的海报是什么原因让堆栈跟踪成为字符串。当堆栈跟踪应该以SLF4J/Logback LOG结尾,但没有或应该抛出异常时,我会这样做:
public void remove(List<String> ids) {
if(ids == null || ids.isEmpty()) {
LOG.warn(
"An empty list (or null) was passed to {}.remove(List). " +
"Clearly, this call is unneccessary, the caller should " +
"avoid making it. A stacktrace follows.",
getClass().getName(),
new Throwable ("Stacktrace")
);
return;
}
// actual work, remove stuff
}
我喜欢它,因为它不需要外部库(当然,除了您的日志后端,它大部分时间都会在那里)。
Arrays.toString(thrown.getStackTrace())
是将结果转换为字符串的最简单方法我在程序中使用这个来打印堆栈跟踪
LOGGER.log(Level.SEVERE, "Query Builder Issue Stack Trace : {0} ,Message : {1} objid {2}", new Object[]{Arrays.toString(e.getStackTrace()), e.getMessage(),objId});
我的oneliner将堆栈跟踪转换为封闭的多行字符串:
Stream.of(e.getStackTrace()).map((a) -> a.toString()).collect(Collectors.joining("\n", "[", "]"))
易于传递给记录器“原样”。
解决方案是将数组的stackTrace转换为字符串数据类型。请参见以下示例:
import java.util.Arrays;
try{
}catch(Exception ex){
String stack = Arrays.toString(ex.getStackTrace());
System.out.println("stack "+ stack);
}
如果您使用的是Java 8,请尝试
Arrays.stream(e.getStackTrace())
.map(s->s.toString())
.collect(Collectors.joining("\n"));
您可以找到Throwable.java提供的getStackTrace()函数的代码:
public StackTraceElement[] getStackTrace() {
return getOurStackTrace().clone();
}
对于StackTraceElement,它提供如下的toString():
public String toString() {
return getClassName() + "." + methodName +
(isNativeMethod() ? "(Native Method)" :
(fileName != null && lineNumber >= 0 ?
"(" + fileName + ":" + lineNumber + ")" :
(fileName != null ? "("+fileName+")" : "(Unknown Source)")));
}
因此,只需使用“\n”连接StackTraceElement。
将堆栈跟踪打印到PrintStream,然后将其转换为字符串:
// ...
catch (Exception e)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(out));
String str = new String(out.toByteArray());
System.out.println(str);
}
选项很少
StringWriter sw=新StringWriter();e.printStackTrace(新的PrintWriter(sw));字符串异常AsString=sw.toString();使用Google Guava libString stackTrace=Throwables.getStackTraceAsString(myException);org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(可丢弃)
import java.io.PrintWriter;
import java.io.StringWriter;
public class PrintStackTrace {
public static void main(String[] args) {
try {
int division = 0 / 0;
} catch (ArithmeticException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
System.out.println(exceptionAsString);
}
}
}
运行程序时,输出将类似:
java.lang.ArithmeticException: / by zero
at PrintStackTrace.main(PrintStackTrace.java:9)
我不久前写了一些方法,所以我想为什么不花我的两分钱。
/** @param stackTraceElements The elements to convert
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements) {
return stackTraceElementsToStr(stackTraceElements, "\n");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements, String lineSeparator) {
return stackTraceElementsToStr(stackTraceElements, lineSeparator, "");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements, String lineSeparator, String padding) {
String str = "";
if(stackTraceElements != null) {
for(StackTraceElement stackTrace : stackTraceElements) {
str += padding + (!stackTrace.toString().startsWith("Caused By") ? "\tat " : "") + stackTrace.toString() + lineSeparator;
}
}
return str;
}
/** @param stackTraceElements The elements to convert
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements) {
return stackTraceCausedByElementsOnlyToStr(stackTraceElements, "\n");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements, String lineSeparator) {
return stackTraceCausedByElementsOnlyToStr(stackTraceElements, lineSeparator, "");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements, String lineSeparator, String padding) {
String str = "";
if(stackTraceElements != null) {
for(StackTraceElement stackTrace : stackTraceElements) {
str += (!stackTrace.toString().startsWith("Caused By") ? "" : padding + stackTrace.toString() + lineSeparator);
}
}
return str;
}
/** @param e The {@link Throwable} to convert
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e) {
return throwableToStrNoStackTraces(e, "\n");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e, String lineSeparator) {
return throwableToStrNoStackTraces(e, lineSeparator, "");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e, String lineSeparator, String padding) {
if(e == null) {
return "null";
}
String str = e.getClass().getName() + ": ";
if((e.getMessage() != null) && !e.getMessage().isEmpty()) {
str += e.getMessage() + lineSeparator;
} else {
str += lineSeparator;
}
str += padding + stackTraceCausedByElementsOnlyToStr(e.getStackTrace(), lineSeparator, padding);
for(Throwable suppressed : e.getSuppressed()) {
str += padding + throwableToStrNoStackTraces(suppressed, lineSeparator, padding + "\t");
}
Throwable cause = e.getCause();
while(cause != null) {
str += padding + "Caused by:" + lineSeparator + throwableToStrNoStackTraces(e.getCause(), lineSeparator, padding);
cause = cause.getCause();
}
return str;
}
/** @param e The {@link Throwable} to convert
* @return The resulting String */
public static final String throwableToStr(Throwable e) {
return throwableToStr(e, "\n");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @return The resulting String */
public static final String throwableToStr(Throwable e, String lineSeparator) {
return throwableToStr(e, lineSeparator, "");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting String */
public static final String throwableToStr(Throwable e, String lineSeparator, String padding) {
if(e == null) {
return "null";
}
String str = padding + e.getClass().getName() + ": ";
if((e.getMessage() != null) && !e.getMessage().isEmpty()) {
str += e.getMessage() + lineSeparator;
} else {
str += lineSeparator;
}
str += padding + stackTraceElementsToStr(e.getStackTrace(), lineSeparator, padding);
for(Throwable suppressed : e.getSuppressed()) {
str += padding + "Suppressed: " + throwableToStr(suppressed, lineSeparator, padding + "\t");
}
Throwable cause = e.getCause();
while(cause != null) {
str += padding + "Caused by:" + lineSeparator + throwableToStr(e.getCause(), lineSeparator, padding);
cause = cause.getCause();
}
return str;
}
例子:
try(InputStream in = new FileInputStream(file)) {
...
} catch(IOException e) {
String exceptionToString = throwableToStr(e);
someLoggingUtility.println(exceptionToString);
...
}
打印:
java.io.FileNotFoundException: C:\test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.gmail.br45entei.Example.main(Example.java:32)
Scala版本
def stackTraceToString(e: Exception): String = {
import java.io.PrintWriter
val sw = new StringWriter()
e.printStackTrace(new PrintWriter(sw))
sw.toString
}
使用Java 8流API,您可以执行以下操作:
Stream
.of(throwable.getStackTrace())
.map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
它将获取堆栈跟踪元素的数组,将它们转换为字符串并连接为多行字符串。
我想知道为什么没有人提到ExceptionUtils.getStackFrames(exception)
对我来说,这是将堆栈跟踪及其所有原因转储到底的最方便方法:
String.join("\n", ExceptionUtils.getStackFrames(exception));
推荐文章
- 在Java中使用UUID的最重要位的碰撞可能性
- 转换列表的最佳方法:map还是foreach?
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母
- Mockito.any()传递带有泛型的接口
- 在IntelliJ 10.5中运行测试时,出现“NoSuchMethodError: org.hamcrest. matcher . descripbemismatch”
- 使用String.split()和多个分隔符
- Java数组有最大大小吗?
- 在Android中将字符串转换为Uri
- 从JSON生成Java类?
- 为什么java.util.Set没有get(int index)?
- Swing和AWT的区别是什么?
- 为什么Java流是一次性的?
- 四舍五入BigDecimal *总是*有两位小数点后
- 设计模式:工厂vs工厂方法vs抽象工厂