将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?
当前回答
警告:不包括原因(通常是有用的位!)
public String stackTraceToString(Throwable e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace()) {
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
其他回答
如果你不想使用外部库,而且你不是为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中可用,这是许多流行开源中最常见的依赖库
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(可丢弃)
老问题,但我想补充一个特殊情况,即您不想打印所有堆栈,通过删除一些您实际上不感兴趣的部分,排除某些类或包。
使用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或其他条件过滤掉。还要注意,这取决于可丢弃的实现细节(不太可能改变,但仍然如此)。
如果你是为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)
以下代码允许您使用字符串格式获取整个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.
}
推荐文章
- 在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抽象工厂