I want to create a custom logger for android application.
The logging should be done in a separate thread as the application generates lots of information. I don’t want to use the Android logs since i need to write the logs in a specific format. Multiple threads will be writing to the log file at the same time, so i have used a queue to keep the log messages
Here is the code that i have
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)
{
}
}
}
Is there any thing wrong with this code? or a better way to create a logging queue
Thanks,
Anuj
Java BlockingQueue implementations already have synchronization concerns built in. Your use of wait, notify, and synchronized is redundant and not needed.
Try mimicking the Producer/Consumer example giving in the BlockingQueue javadoc