adding the rateSampler

This commit is contained in:
Guillaume Polaert 2017-04-27 17:54:14 +02:00
parent a30b13f9fa
commit 412cf7e67a
3 changed files with 69 additions and 7 deletions

View File

@ -0,0 +1,32 @@
package com.datadoghq.trace;
import com.datadoghq.trace.impl.DDSpan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RateSampler implements Sampler {
private final static Logger logger = LoggerFactory.getLogger(RateSampler.class);
private final double sampleRate;
public RateSampler(double sampleRate) {
if (sampleRate <= 0) {
sampleRate = 1;
logger.error("SampleRate is negative or null, disabling the sampler");
} else if (sampleRate > 1) {
sampleRate = 1;
}
this.sampleRate = sampleRate;
logger.debug("Initializing the RateSampler, sampleRate=" + this.sampleRate * 100 + "%");
}
@Override
public boolean sample(DDSpan span) {
return Math.random() <= this.sampleRate;
}
}

View File

@ -0,0 +1,32 @@
package com.datadoghq.trace;
import com.datadoghq.trace.impl.DDSpan;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class RateSamplerTest {
@Test
public void testRateSampler() {
DDSpan mockSpan = mock(DDSpan.class);
final double sampleRate = 0.35;
final int iterations = 100000;
Sampler sampler = new RateSampler(sampleRate);
int kept = 0;
for (int i = 0; i < iterations; i++) {
if (sampler.sample(mockSpan)) {
kept++;
}
}
assertThat(((double) kept / iterations)).isBetween(sampleRate - 0.01, sampleRate + 0.01);
}
}

View File

@ -134,6 +134,7 @@ public class DDSpanBuilderTest {
when(mockedSpan.context()).thenReturn(mockedContext); when(mockedSpan.context()).thenReturn(mockedContext);
when(mockedContext.getSpanId()).thenReturn(spanId); when(mockedContext.getSpanId()).thenReturn(spanId);
when(mockedContext.getServiceName()).thenReturn("foo");
final String expectedName = "fakeName"; final String expectedName = "fakeName";
@ -210,13 +211,10 @@ public class DDSpanBuilderTest {
assertThat(spans.get((int) (Math.random() * nbSamples)).context.getTrace()).containsAll(spans); assertThat(spans.get((int) (Math.random() * nbSamples)).context.getTrace()).containsAll(spans);
root.finish(); root.finish();
//TODO Check order
//assertThat(root.getTrace()).containsExactly(spans) // not comparing the nano
assertThat(spans.get(1).durationNano).isEqualTo((tickEnd - tickStart) * 1000000L); assertThat(spans.get(1).durationNano / 1000000L).isEqualTo((tickEnd - tickStart));
for (DDSpan span : spans) {
assertThat(span.getDurationNano()).isNotNull();
assertThat(span.getDurationNano()).isNotZero();
}
} }