Android Log.X无法打印堆栈跟踪信息。

18

e.printStackTrace() 工作正常(即将我的堆栈跟踪打印到 stderr),但 Log.X 无法打印任何堆栈跟踪。

例如:

} catch (IOException e) {
    Log.e("Network", "Exception", e);
    e.printStackTrace();
}

输出:

08-31 03:46:21.992: W/Network(13238): Exception
08-31 03:46:22.092: W/System.err(13238): java.net.UnknownHostException: Unable to resolve host "...": No address associated with hostname
08-31 03:46:22.204: W/System.err(13238):    at java.net.InetAddress.lookupHostByName(InetAddress.java:394)
08-31 03:46:22.222: W/System.err(13238):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:46:22.222: W/System.err(13238):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
2个回答

44
Android的Log.getStackTraceString被Log.X使用时会吞噬UnknownHostException异常。 :(
来源:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/util/Log.java#Log.getStackTraceString%28java.lang.Throwable%29
public static String getStackTraceString(Throwable tr) {
    if (tr == null) {
        return "";
    }

    // This is to reduce the amount of log spew that apps do in the non-error
    // condition of the network being unavailable.
    Throwable t = tr;
    while (t != null) {
        if (t instanceof UnknownHostException) {
            return "";
        }
        t = t.getCause();
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    tr.printStackTrace(pw);
    return sw.toString();
}

“减少日志输出很好,但连我的异常信息都不告诉我,这太糟糕了!”

6
好的,我理解了。翻译如下:那就解释了这个问题。我认为这是安卓系统的一个漏洞。 - dhakim
6
这太蠢了,愚蠢而反对开发者 - 即使应用程序记录UnknownHostException又怎样?可能有理由!还有多少其他异常以这种愚蠢的方式隐藏起来?Android对开发人员来说真的很难。 - Martin Vysny
对于其他遇到空堆栈跟踪的人来说,这仍然是一个正确的答案,即使是在7年后。 - Alex N.
快到2022年底了,这个问题仍然存在。 - Shadow

0

我之前也遇到过这种问题,所以我创建了一个Xposed模块来解决这个问题。请参考适用于Android 8+的Xposed原始的Xposed进行安装。后来我偶然发现了这个帖子。

这是项目链接:FullStackTrace

在发布版本中还有一个apk可供下载。

您的设备必须已经root才能使用Xposed。我在这里使用了Magisk


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接