2016-05-16 61 views
0

我想将我的android应用程序日志保存在文本文件中并通过电子邮件发送,以便处理异常和反馈。我在我的应用程序中实现了以下代码,但日志文本文件不包含任何内容,并且在执行代码后为空。将应用程序日志保存到文本文件不起作用

try { 
     Process process = Runtime.getRuntime().exec("logcat -d"); 
     BufferedReader bufferedReader = new BufferedReader(
       new InputStreamReader(process.getInputStream())); 

     StringBuilder logString = new StringBuilder(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      logString.append(line); 
     } 

     File logFile = new File("sdcard/log.txt"); 
     if (!logFile.exists()) { 
      try { 
       logFile.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
     buf.append(logString); 
     buf.newLine(); 
     buf.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

我用Log.iLog.eLog.w写日志消息在我的整个应用程序的logcat。

如果有人指导我解决我的问题,我将不胜感激。

回答

2

试试这个,

public static void appendLog(String text) { 
    if (true) { 

     File root = android.os.Environment.getExternalStorageDirectory(); 
     File dir = new File(root.getAbsolutePath() + "/YourAppName"); 
     dir.mkdir(); 
     File logFile = new File(dir, "YourAppName.txt"); 

     if (!logFile.exists()) { 
      try { 
       logFile.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     try { 
      // BufferedWriter for performance, true to set append to file 
      // flag 
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, 
        true)); 
      buf.append(text 
        + " - " 
        + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") 
          .format(new Date())); 
      buf.newLine(); 
      buf.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

,并用此方法,而不是Log.iLog.eLog.w在您的应用程序

+0

尝试过解释的变化让其他人后来检查你的答案可以理解太 – Shubhank

+0

我不明白你为什么使用'Process'作为追加日志?实际上,当你使用'BufferedWriter'时,它包装一个现有的Writer并缓冲输出。所以不需要使用'Process'和其他方法。只需获取文件并在前一个日志中写入(附加)您的日志。 –

+0

@AbhishekPatel感谢您的快速回答。我使用Process来访问系统日志。根据你的回答,我无法跟踪未处理的异常甚至崩溃。只有附加的日志可以被监控。 – mohammad

相关问题