Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

retrieveLogsAndClear works in constant space #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
package com.hextremelabs.cloudwatchappender;

import com.amazonaws.annotation.ThreadSafe;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.Comparator.comparing;

/**
* @author oladeji
*/
@ThreadSafe
public class CloudWatchAppender extends AppenderSkeleton {

private static final Queue<LoggingEvent> LOGS = new ConcurrentLinkedQueue<>();
private static final int INITIAL_CAPACITY = 11; // copied from PBQ implementation
private static final AtomicReference<Queue<LoggingEvent>> LOGS = new AtomicReference<>(
new PriorityBlockingQueue<>(INITIAL_CAPACITY, comparing(LoggingEvent::getTimeStamp)));

@Override
protected void append(LoggingEvent loggingEvent) {
LOGS.add(loggingEvent);
LOGS.updateAndGet(queue -> {
queue.add(loggingEvent);
return queue;
});
}

@Override
Expand All @@ -32,10 +37,8 @@ public boolean requiresLayout() {
return true;
}

public static Collection<LoggingEvent> retrieveLogsAndClear() {
final List<LoggingEvent> events = new LinkedList<>();
LOGS.removeIf(e -> events.add(e));
events.sort(comparing(LoggingEvent::getTimeStamp));
return events;
static Collection<LoggingEvent> retrieveLogsAndClear() {
Queue<LoggingEvent> queue = new PriorityBlockingQueue<>(INITIAL_CAPACITY, comparing(LoggingEvent::getTimeStamp));
return LOGS.getAndSet(queue);
}
}