自定义 Android 应用程序日志记录

14
我想为Android应用程序创建一个自定义日志记录器。由于应用程序生成大量信息,因此应该在单独的线程中进行记录。我不想使用Android logs,因为我需要按特定格式编写日志。多个线程将同时写入日志文件,因此我已经使用队列来保存日志消息。
这是我拥有的代码:
Queue<LogEntry> logQueue = new LinkedBlockingQueue<LogEntry>();
LogWritterThread logWritterThread = new LogWritterThread();

// to queue the log messages
public void QueueLogEntry(String message)
{
    LogEntry le = new LogEntry(message);
    {
        logQueue.add(le);
        logQueue.notifyAll();
    }

logWritterThread.start();
}

    class LogWritterThread extends Thread 
{
    public void run() 
    {
        try 
        {
            while(true)
            {
                //thread waits until there are any logs to write in the queue
                if(logQueue.peek() == null)
                    synchronized(logQueue){
                        logQueue.wait();
                    }
                if(logQueue.peek() != null)
                {
                    LogEntry logEntry;
                    synchronized(logQueue){
                        logEntry = logQueue.poll();
                    }

                    // write the message to file
                }
                if(Thread.interrupted())
                    break;
            }
        } 
        catch (InterruptedException e) 
        {                
        }
    }
}

这段代码有问题吗?还是有更好的方法来创建日志队列?

谢谢, Anuj

2个回答

6

Java的BlockingQueue实现已经内置了同步问题。您使用wait、notify和synchronized是多余且不必要的。

尝试模仿BlockingQueue javadoc中提供的生产者/消费者示例。

class LogEntry {
  private final String message;

  LogEntry(String msg) {
    message = msg;
  }
}

class LogProducer {
   private final BlockingQueue<LogEntry> queue;

   LogProducer(BlockingQueue<LogEntry> q) {
     queue = q;
   }

   public void log(String msg) {
      queue.put(new LogEntry(msg));
   }
 }

class LogConsumer implements Runnable {
   private final BlockingQueue<LogEntry> queue;

   LogConsumer(BlockingQueue<LogEntry> q) {
     queue = q;
   }

   public void run() {
     try {
       while(true) {
         LogEntry entry = queue.take();
         // do something with entry
       }
     } catch(InterruptedException ex) {
       // handle
     }
   }
}

class Setup {
  public static void main(String[] args) {
    BlockingQueue<LogEntry> queue = new LinkedBlockingQueue<LogEntry>();
    LogConsumer c = new LogConsumer(queue);
    new Thread(c).start();

    LogProducer p = new LogProducer(queue);
    p.log("asynch");
    p.log("logging");
  }
}

2
我会使用Handler——因为它们实现了一个队列和一个消息线程,这些都是线程安全的。这意味着你可以创建一个扩展Handler的类,并在整个项目中使用该类。使用几行代码,你就可以大大缩小现有代码的体积。
谷歌的文档: http://developer.android.com/reference/android/os/Handler.html 这是一个非常简单的例子: http://saigeethamn.blogspot.com/2010/04/threads-and-handlers-android-developer.html 这是一个更好的例子,因为他们使用“msg.what”来决定要做什么(这对于不同级别的日志记录很有用): https://idlesun.wordpress.com/2010/12/12/android-handler-and-message-tutorial/

谢谢您的帮助...不幸的是,我不能将它们都标记为答案。 - Anuj Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接