如何连续读取logcat并写入内部存储文件?

时间:2018-10-10 09:05:41

标签: android logging logcat

为此,我不断尝试读取logcat并将其写入内部存储。

public class LogCatTask extends AsyncTask<Void, String, Void> {
    public AtomicBoolean run = new AtomicBoolean(true);

    @Override
    protected Void doInBackground(Void... params) {
        try {

            //create text file in SDCard
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
            dir.mkdirs();
            File file = new File(dir, "logcat.txt");

            Runtime.getRuntime().exec("logcat -c");
            Process process = Runtime.getRuntime().exec("logcat -f "+file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder log = new StringBuilder();
            String line = "";
            Log.e("log cat task...","while...run.get()."+run.get());
            while (run.get()) {
                line = bufferedReader.readLine();
                //Log.e("log cat task...","while...out.");
                if (line != null) {
                    Log.e("log cat task...","while....");
                    log.append(line);
                    //publishProgress(log.toString());

                    //to write logcat in text file
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);

                    // Write the string to the file
                    osw.write(log.toString());
                    osw.flush();
                    osw.close();
                }
                line = null;
                Thread.sleep(10);
                //Log.e("log cat task...","while...out.");
            }
            //Log.e("log cat task...","ouet....while....");
        }
        catch(Exception ex){

        }
        return null;
    }
}

上面的代码运行后,它会读取logcat并将其写入存储,但是最多会读取一部分日志,而不是读取连续记录。如何连续读取logcat?

1 个答案:

答案 0 :(得分:0)

这是一个有效的代码段

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

        StringBuilder log=new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            // do what you want with the line you just read
            // you're in an infinite loop continuously reading the log,
            // you might want to add some mechanism to break out of it
        }
    }
    catch (IOException  e) {
        fail("failed to get log");
    }

您的代码过于复杂,容易出现竞争状况。例如,保证logcat -c在logcat -f命令之前完成。 -f命令将输出重定向到文件,并且您的逻辑也在尝试写入同一文件。这是非常有问题的。我注意到某些logcat选项(例如“ -T”)无法以编程方式工作。也许“ -f”选项也有问题。如果您只想读取当前时间之前的日志文件,请使用“ logcat -d”。