2015-01-15 55 views
6

我已閱讀this article。但它似乎大部分文本顯示不在我的應用程序。我如何過濾郵件並讓它只顯示我的應用程序的日誌。換句話說,我想在Android Studio中顯示它(僅顯示來自我的應用程序的錯誤日誌,顯示時間戳等):以編程方式讀取logcat以獲得應用程序

我嘗試了類似「logcat -d -v time」的內容,但不起作用。任何想法?謝謝。

enter image description here

+1

你總是可以從logcat的自己解析線,而忽略你不希望任何標記。 –

回答

15

嘗試下面的代碼只得到您的應用程序的日誌。

public final class MyAppLogReader { 

    private static final String TAG = MyAppLogReader.class.getCanonicalName(); 
    private static final String processId = Integer.toString(android.os.Process 
      .myPid()); 

    public static StringBuilder getLog() { 

     StringBuilder builder = new StringBuilder(); 

     try { 
      String[] command = new String[] { "logcat", "-d", "-v", "threadtime" }; 

      Process process = Runtime.getRuntime().exec(command); 

      BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(process.getInputStream())); 

      String line; 
      while ((line = bufferedReader.readLine()) != null) { 
       if (line.contains(processId)) { 
        builder.append(line); 
        //Code here 
       } 
      } 
     } catch (IOException ex) { 
      Log.e(TAG, "getLog failed", ex); 
     } 

     return builder; 
    } 
} 

編輯

添加以下權限到你的AndroidManifest文件

<uses-permission android:name="android.permission.READ_LOGS" /> 
+1

閱讀日誌的延遲是多少? – Sid

+3

我編輯你的文章,通過添加-d命令行參數logcat,否則函數永遠不會返回,只是等待並添加更多的日誌行,因爲他們發佈。同樣在Android的新版本(我認爲從Jellybean上來)和沒有root權限的情況下,只有你自己的應用程序包生成的logcat條目包含在內。 – gregko

+0

@gregko感謝您的編輯:) –

相關問題