Java / Android - 如何打印出完整的堆栈跟踪?

2022-08-31 08:05:46

在 Android (Java) 中,如何打印出完整的堆栈跟踪?如果我的应用程序从nullPointerException或其他原因崩溃,它会打印出一个(几乎)完整的堆栈跟踪,如下所示:

java.io.IOException: Attempted read from closed stream.
com.android.music.sync.common.SoftSyncException: java.io.IOException: Attempted read from closed stream.
    at com.android.music.sync.google.MusicSyncAdapter.getChangesFromServerAsDom(MusicSyncAdapter.java:545)
    at com.android.music.sync.google.MusicSyncAdapter.fetchDataFromServer(MusicSyncAdapter.java:488)
    at com.android.music.sync.common.AbstractSyncAdapter.download(AbstractSyncAdapter.java:417)
    at com.android.music.sync.common.AbstractSyncAdapter.innerPerformSync(AbstractSyncAdapter.java:313)
    at com.android.music.sync.common.AbstractSyncAdapter.onPerformLoggedSync(AbstractSyncAdapter.java:243)
    at com.google.android.common.LoggingThreadedSyncAdapter.onPerformSync(LoggingThreadedSyncAdapter.java:33)
    at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:164)
Caused by: java.io.IOException: Attempted read from closed stream.
    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:148)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
    at java.util.zip.GZIPInputStream.readFully(GZIPInputStream.java:212)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:64)
    at android.net.http.AndroidHttpClient.getUngzippedContent(AndroidHttpClient.java:218)
    at com.android.music.sync.api.MusicApiClientImpl.createAndExecuteMethod(MusicApiClientImpl.java:312)
    at com.android.music.sync.api.MusicApiClientImpl.getItems(MusicApiClientImpl.java:588)
    at com.android.music.sync.api.MusicApiClientImpl.getTracks(MusicApiClientImpl.java:638)
    at com.android.music.sync.google.MusicSyncAdapter.getChangesFromServerAsDom(MusicSyncAdapter.java:512)
    ... 6 more

但是,有时,出于调试目的,我希望从代码中的位置记录完整的堆栈跟踪。我想我可以这样做:

StackTraceElement trace = new Exception().getStackTrace();
Log.d("myapp", trace.toString());

但这只会打印出指向对象的指针...我是否必须循环访问所有堆栈跟踪元素才能将其打印出来?还是有一种简单的方法可以将其全部打印出来?


答案 1

以下操作应该可以解决问题:

Log.d("myapp", Log.getStackTraceString(new Exception()));

请注意,最后不会从堆栈跟踪中截取任何信息:...x more

(这表示)此异常的堆栈跟踪的其余部分与此异常(“封闭”异常)引起的异常的堆栈跟踪底部的指示帧数匹配。

...或者换句话说,替换为第一个异常的最后一行。x morex


答案 2

所有带有签名的日志方法都有覆盖。(String tag, String msg, Throwable tr)

将异常作为第个参数传递应该会为您提供 logcat 中的完整堆栈跟踪。