Skip to content

Instantly share code, notes, and snippets.

@mveitas
Created March 19, 2014 12:22
Show Gist options
  • Save mveitas/9640545 to your computer and use it in GitHub Desktop.
Save mveitas/9640545 to your computer and use it in GitHub Desktop.
FilteredAppenderFactoryTest
package io.dropwizard.logging;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.fest.assertions.api.Assertions.assertThat;
public class FilteredAppenderFactoryTest {
private Set<FilterReply> filterReplies;
@Before
public void setup() {
filterReplies = new HashSet<>();
}
@Test
public void isFiltering() throws Exception {
for (FilterReply reply : FilterReply.values()) {
FilteredAppenderFactory filteredAppenderFactory = new FilteredAppenderFactory();
filteredAppenderFactory.setFilterReply(reply);
Appender<ILoggingEvent> appender = filteredAppenderFactory
.build(new LoggerContext(), "MyApplication", null);
appender.doAppend(new TestLoggingEvent(reply));
Thread.sleep(filteredAppenderFactory.getBatchDuration().toMilliseconds() + 100);
}
assertThat(filterReplies).containsOnly(FilterReply.ACCEPT, FilterReply.NEUTRAL);
}
class TestLoggingEvent extends LoggingEvent {
private final FilterReply reply;
TestLoggingEvent(FilterReply reply) {
this.reply = reply;
}
public FilterReply getReply() {
return reply;
}
}
@JsonTypeName("filtered")
class FilteredAppenderFactory extends AbstractAppenderFactory {
private FilterReply reply;
@JsonProperty
public void setFilterReply(FilterReply reply) {
this.reply = reply;
}
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, Layout<ILoggingEvent> layout) {
final MyAppender appender = new MyAppender();
appender.setName("filtered-appender");
appender.setContext(context);
Filter<ILoggingEvent> filter = new Filter<ILoggingEvent>() {
@Override
public FilterReply decide(ILoggingEvent event) {
return reply;
}
};
filter.start();
// Adding a filter to original Appender
appender.addFilter(filter);
appender.start();
// AsyncAppender does not have any Filters
Appender<ILoggingEvent> async = wrapAsync(appender);
return async;
}
class MyAppender extends AppenderBase<ILoggingEvent> {
@Override
protected void append(ILoggingEvent eventObject) {
TestLoggingEvent testLoggingEvent = (TestLoggingEvent)eventObject;
filterReplies.add(testLoggingEvent.getReply());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment