Android - print full exception backtrace to log

前端 未结 9 1435
萌比男神i
萌比男神i 2020-11-29 23:02

I have a try/catch block that throws an exception and I would like to see information about the exception in the Android device log.

I read the log of the mobile de

相关标签:
9条回答
  • 2020-11-29 23:10
    public String getStackTrace(Exception e){
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      return sw.toString();
    }
    
    0 讨论(0)
  • 2020-11-29 23:11
    try {
        // code that might throw an exception
    } catch (Exception e) {
        Log.e("MYAPP", "exception", e);
    }
    

    More Explicitly with Further Info

    (Since this is the oldest question about this.)

    The three-argument Android log methods will print the stack trace for an Exception that is provided as the third parameter. For example

    Log.d(String tag, String msg, Throwable tr)
    

    where tr is the Exception.

    According to this comment those Log methods "use the getStackTraceString() method ... behind the scenes" to do that.

    0 讨论(0)
  • 2020-11-29 23:13

    KOTLIN SOLUTION:

    You can make use of the helper function getStackTraceString() belonging to the android.util.Log class to print the entire error message on console.

    Example:

    try { 
     
       // your code here
        
    } catch (e: Exception) {
    
         Log.e("TAG", "Exception occurred, stack trace: " + e.getStackTraceString());
    
    }
    
    0 讨论(0)
  • 2020-11-29 23:14

    This helper function also works nice since Exception is also a Throwable.

        try{
            //bugtastic code here
        }
        catch (Exception e)
        {
             Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
        }
    
    0 讨论(0)
  • 2020-11-29 23:19
    catch (Exception e) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PrintStream stream = new PrintStream( baos );
      e.printStackTrace(stream);
      stream.flush();
      Log.e("MYAPP", new String( baos.toByteArray() );
    }
    

    Or... ya know... what EboMike said.

    0 讨论(0)
  • 2020-11-29 23:23

    The standard output and error output are directed to /dev/null by default so it is all lost. If you want to log this output then you need to follow the instructions "Viewing stdout and stderr" shown here

    0 讨论(0)
提交回复
热议问题