android – Saving Logcat output as application text file: crashes unexpectedly when there are few (or no) events

I’ve added a method to my application that creates a Logcat file of that session.

public void LogcatToTextFile() {
    Date T = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String szDateTime = sdf.format(T);
    SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
    String szDate = date.format(T);

    //makes ApplicationLogFiles directory if there is none
    File logFileDirectory = new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "ApplicationLogFiles");
    logFileDirectory.mkdir();
    //makes a directory that is titled with today's date if there is none
    File logFileDateDirectory = new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/ApplicationLogFiles/" + szDate);
    logFileDateDirectory.mkdir();
    //defines actual logFile in the nested directories
    File logFile = new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/ApplicationLogFiles/" + szDate, "ApplicationLogCatFiles_" + szDateTime + ".txt");

    if (!logFile.exists()) {
        try {
            Process process = Runtime.getRuntime().exec("logcat -c"); 
            process = Runtime.getRuntime().exec("logcat -f " + logFile + " *:V");
        }
        catch (IOException e) {
           e.printStackTrace();
            Log.e("IOException", "exception in LogcatToTextFile() method");
        }
    }
}

This runs fine as long as regular events (Log.d) are being logged frequently.
Some sessions have lasted more than ten hours (50,000 rows) until the application is exited by the user.
However, without frequent log events, Logcat stops after a short period of time (minutes to an hour) when there are no events to log.
I would like for it to keep running and document any errors that may occur.

Note: Similar problem noted here: logcat stops writing to file on device

Read more here: Source link