Anu*_*pta 13 java logging android
我想为Android应用程序创建一个自定义记录器.当应用程序生成大量信息时,应在单独的线程中完成日志记录.我不想使用Android日志,因为我需要以特定格式编写日志.多个线程将同时写入日志文件,因此我使用队列来保留日志消息
这是我的代码
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)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码有什么问题吗?或者是创建日志记录队列的更好方法
谢谢,Anuj
Java BlockingQueue实现已经内置了同步问题.您对wait,notify和synchronized的使用是多余的,不需要.
尝试模仿BlockingQueue javadoc中的Producer/Consumer示例
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");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5269 次 |
| 最近记录: |