如何持续监控LogCat文件?

时间:2011-01-11 18:31:16

标签: android logging monitoring logcat continuous

我需要以某种方式监视LogCat日志,这意味着当我的服务正在运行时,我需要读取LogCat以获取新条目。 此刻我只知道如何检索Log:

Process mLogcatProc = null;
    BufferedReader reader = null;
    try
    {
            mLogcatProc = Runtime.getRuntime().exec(new String[]
                   {"logcat", "-d", "ActivityManager:I *:S" });        

            reader = new BufferedReader(new InputStreamReader
    (mLogcatProc.getInputStream()));

            String line;
            final StringBuilder log = new StringBuilder();
            String separator = System.getProperty("line.separator"); 

            while ((line = reader.readLine()) != null)
            {
                    log.append(line);
                    log.append(separator);
            }

如果我删除-d选项,它将不会退出,但它也不会起作用。 那么如何修改波纹管代码以便从LogCat中连续读取新条目?

2 个答案:

答案 0 :(得分:6)

这是我如何做到的,使用刘嘉豪的建议:

ReadThread thread;

public void startRecordingLogs()
{
  if(thread == null || !thread.isAlive())
  {
    ReadThread thread = new ReadThread();
    thread.start();
  }
}

public String stopRecordingLogs()
{
  String results = thread.stopLogging();
  return results;
}

private class ReadThread extends Thread{

  String results;
  Process process;
  Object lockObject = new Object();

  public void run(){
    synchronized(lockObject)
    {
      process = Runtime.getRuntime().exec("logcat -v time");        

      reader = new BufferedReader(new InputStreamReader (process.getInputStream()));

      String line;
      final StringBuilder log = new StringBuilder();
      String separator = System.getProperty("line.separator"); 

      while ((line = reader.readLine()) != null)
      {
        log.append(line);
        log.append(separator);
      }
    }

    results = log.toString();
  }

  public String stopLogging()
  {
    process.destroy();
    synchronized(lockObject)
    {
      return results;
    }
  }
}

答案 1 :(得分:2)

您可以在后台创建一个新线程来运行logcat(不带选项-d)。

注意:使用缓冲事件而不是进程ActivityManager,它更准确。 “logcat -b events”