17

e.printStackTrace() works fine (i.e. prints my stacktrace to stderr) but Log.X fails to print a stacktrace at all.

For example:

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

Output:

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)
ostergaard
  • 3,377
  • 2
  • 30
  • 40

2 Answers2

43

Turns out Android's Log.getStackTraceString which is used by Log.X swallows UnknownHostException. :(

From: 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();
}

It's all very well reducing log spew but to not even tell me what my exception was is bad joojoo!

ostergaard
  • 3,377
  • 2
  • 30
  • 40
  • 5
    Well that explains that. I'd consider this a bug in Android. – dhakim Aug 21 '14 at 14:09
  • 5
    This is just plain stupid, moronic and anti-developer - so what if the app logs UnknownHostException? There may be a reason for that! How many other exceptions are hidden in this moronic way??? Android is sooo hard to develop for. – Martin Vysny Nov 23 '15 at 15:32
  • For anyone else stumbling through empty stack traces, this is strangely still a correct answer 7 years later. – Alex N. Jul 30 '20 at 21:41
  • It's almost the end of 2022, this is still a problem. – Shadow Nov 25 '22 at 20:22
0

I had also this kind of issue and created an Xposed module to overcome this problem. See Xposed for Android 8+ or the Original Xposed for installation instruction. Later I stumbled over this thread.

Here is the project: FullStackTrace

There is also an apk for the download unser the releases.

You device must be rooted to be able to use Xposed. I used Magisk here.

k_o_
  • 5,143
  • 1
  • 34
  • 43