Reading logs programatically


SDK Version: 
M3

Writing logs into logcat from yuor application is quite easy, reading the logcat programmatically is just a bit more tricky.
Reading logs is usually used for bugreport purposes.

logcat

The following code reads logs and displays then in a TextView:

  1. public class LogTest extends Activity {
  2.   @Override
  3.   public void onCreate(Bundle savedInstanceState) {
  4.     super.onCreate(savedInstanceState);
  5.     setContentView(R.layout.main);
  6.     try {
  7.       Process process = Runtime.getRuntime().exec("logcat -d");
  8.       BufferedReader bufferedReader = new BufferedReader(
  9.       new InputStreamReader(process.getInputStream()));
  10.                        
  11.       StringBuilder log=new StringBuilder();
  12.       String line;
  13.       while ((line = bufferedReader.readLine()) != null) {
  14.         log.append(line);
  15.       }
  16.       TextView tv = (TextView)findViewById(R.id.textView1);
  17.       tv.setText(log.toString());
  18.     } catch (IOException e) {
  19.     }
  20.   }
  21. }

When I first fint this solution, I was afraid that it will require some extreme permission because it runs logcat like a console command.
Fortunatelly there is a permission for reading logs:

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

You can add any more parameters to the logcat command string, just like it is defined in the documentation.

When implementing a bugreport feature, with sending logs to yuorself, dont forget that many applications outputs personal information into the logcat, so a policy about them is definetly needed.