将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?


当前回答

警告:这可能有点离题,但哦,好吧…;)

我不知道最初的海报是什么原因让堆栈跟踪成为字符串。当堆栈跟踪应该以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
}

我喜欢它,因为它不需要外部库(当然,除了您的日志后端,它大部分时间都会在那里)。

其他回答

以下代码允许您使用字符串格式获取整个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.
}

如果你是为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)

老问题,但我想补充一个特殊情况,即您不想打印所有堆栈,通过删除一些您实际上不感兴趣的部分,排除某些类或包。

使用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或其他条件过滤掉。还要注意,这取决于可丢弃的实现细节(不太可能改变,但仍然如此)。

使用Java 8流API,您可以执行以下操作:

Stream
    .of(throwable.getStackTrace())
    .map(StackTraceElement::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);
}