2013-08-31 120 views
9

e.printStackTrace()工作正常(即打印我的堆栈跟踪到stderr)但Log.X根本无法打印堆栈跟踪。Android 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) 

回答

21

原来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(); 
} 

这一切都非常好减少日志喷涌但甚至没有告诉我有什么例外的是不好的JooJoo

+3

那么这解释了我会考虑这个!在Android中的一个错误 – dhakim

+3

至少应该记录getMessage,如果不是堆栈跟踪... – Oliv

+2

这只是简单的愚蠢,愚蠢和反开发人员 - 那么如果应用程序记录UnknownHostException呢?这可能是一个原因!很多其他的例外都是以这种诡异的方式隐藏起来的?Android很难为之发展。 –