Write android logcat data to a file

Solution 1:

Here is an example of reading the logs.

You could change this to write to a file instead of to a TextView.

Need permission in AndroidManifest:

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

Code:

public class LogTest extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    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) {
    }
  }
}

Solution 2:

Logcat can write directly to a file:

public static void saveLogcatToFile(Context context) {    
    String fileName = "logcat_"+System.currentTimeMillis()+".txt";
    File outputFile = new File(context.getExternalCacheDir(),fileName);
    @SuppressWarnings("unused")
    Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath());
}

more info on logcat: see http://developer.android.com/tools/debugging/debugging-log.html

Solution 3:

Or you can try this variant

try {
    final File path = new File(
            Environment.getExternalStorageDirectory(), "DBO_logs5");
    if (!path.exists()) {
        path.mkdir();
    }
    Runtime.getRuntime().exec(
            "logcat  -d -f " + path + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace();
}