如何只将应用程序日志写入android中的外部文件

时间:2012-11-21 12:30:49

标签: android

我正在尝试将应用程序的日志写入外部文件。我的日志就像Log.e(“Offset”,“”+ mOffset);我使用以下代码:

public String writeLogToFile()
{
    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);
                }
            bufferedReader.close();
            return log.toString();
        } 
    catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
}

它还会打印系统级别的所有日志。是的我放-d所以它是打印但如果我把-e或-i它不写文件。我只想写Log.e("Offset",""+mOffset)。我在哪里做错了?

1 个答案:

答案 0 :(得分:1)

以下是如何读取当前应用程序的日志。要过滤日志,我获取进程ID(pid)并将其与logcat输出的每一行进行比较。

在logcat的参数中,我指定读取最后200行并随时间显示日志。

public String writeLogToFile() {
    StringBuilder logs = new StringBuilder();
    int pid = android.os.Process.myPid();
    String pidPattern = String.format("%d):", pid);
    try {
        Process process = new ProcessBuilder()
                .command("logcat", "-t", "200", "-v", "time")
                .redirectErrorStream(true)
                .start();

        InputStream in = null;

        try {
            in = process.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(pidPattern)) {
                    logs.append(line).append("\n");
                }
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.e(TAG, "Cannot close input stream", e);
                }
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Cannot read logs", e);
    }

    return log.toString();
}