当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How to constanly monitor LogCat file?

问题描述:

I need to somehow monitor the LogCat log, meaning that while my service is running I need to read the LogCat for new entries.

At this moment I know only how to retrieve once the 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);

}

If I remove the -d option it will not exit but also it will not either work.

So how can I modify the bellow code in order to continuously read new entries from LogCat?

网友答案:

This is how I did it, using Jiahao Liu's suggestion:

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;
    }
  }
}
网友答案:

You can create a new thread to running the logcat(without the option -d) in the background.

Note: Use the buffer events instead of the process ActivityManager, it is more accurate. "logcat -b events"

分享给朋友:
您可能感兴趣的文章:
随机阅读: