Align counter behaviour between metric exporters

The MetricCopyExporter has had the capability for a while to keep
track of counters internally. This change aligns that with the
PrefixMetricGroupExporter.

Fixes gh-5762
This commit is contained in:
Dave Syer 2016-04-21 14:00:12 +01:00
parent 97934aaf82
commit de0f0ecce4
2 changed files with 35 additions and 1 deletions

View File

@ -19,10 +19,13 @@ package org.springframework.boot.actuate.metrics.export;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.boot.actuate.metrics.reader.PrefixMetricReader;
import org.springframework.boot.actuate.metrics.repository.MultiMetricRepository;
import org.springframework.boot.actuate.metrics.writer.Delta;
import org.springframework.boot.actuate.metrics.writer.PrefixMetricWriter;
/**
@ -38,6 +41,8 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter {
private final PrefixMetricWriter writer;
private ConcurrentMap<String, Long> counts = new ConcurrentHashMap<String, Long>();
private Set<String> groups = new HashSet<String>();
/**
@ -88,7 +93,26 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter {
@Override
protected void write(String group, Collection<Metric<?>> values) {
this.writer.set(group, values);
if (group.contains("counter.")) {
for (Metric<?> value : values) {
this.writer.increment(group, calculateDelta(value));
}
}
else {
this.writer.set(group, values);
}
}
private Delta<?> calculateDelta(Metric<?> value) {
long delta = value.getValue().longValue();
Long old = this.counts.replace(value.getName(), delta);
if (old != null) {
delta = delta - old;
}
else {
this.counts.putIfAbsent(value.getName(), delta);
}
return new Delta<Long>(value.getName(), delta, value.getTimestamp());
}
}

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.boot.actuate.metrics.Iterables;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository;
import org.springframework.boot.actuate.metrics.writer.Delta;
import static org.junit.Assert.assertEquals;
@ -50,6 +51,15 @@ public class PrefixMetricGroupExporterTests {
assertEquals(1, Iterables.collection(this.writer.groups()).size());
}
@Test
public void countersIncremented() {
this.writer.increment("counter.foo", new Delta<Long>("bar", 1L));
this.reader.set(new Metric<Number>("counter.foo.bar", 1));
this.exporter.setGroups(Collections.singleton("counter.foo"));
this.exporter.export();
assertEquals(2L, this.writer.findAll("counter.foo").iterator().next().getValue());
}
@Test
public void unprefixedMetricsNotCopied() {
this.reader.set(new Metric<Number>("foo.bar", 2.3));