Read logcat programmatically within application

David picture David · Oct 2, 2012 · Viewed 73k times · Source

I want to read and react to logcat logs within my application.

I found the following code:

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

  StringBuilder log=new StringBuilder();
  String line = "";
  while ((line = bufferedReader.readLine()) != null) {
    log.append(line);
  }
  TextView tv = (TextView)findViewById(R.id.textView1);
  tv.setText(log.toString());
  } 
catch (IOException e) {}

This code indeed returns the logcat logs that made until the application was started -

But is it possible to continuously listen to even new logcat logs?

Answer

Luis picture Luis · Oct 2, 2012

You can keep reading the logs, just by removing the "-d" flag in your code above.

The "-d" flag instruct to logcat to show log content and exit. If you remove the flag, logcat will not terminate and keeps sending any new line added to it.

Just have in mind that this may block your application if not correctly designed.

good luck.