下面列出了com.codahale.metrics.ScheduledReporter#report ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Print out reports from the executed tests.
*/
public void printReport() {
ScheduledReporter reporter = freonCommand.isInteractive()
? ConsoleReporter.forRegistry(metrics).build()
: Slf4jReporter.forRegistry(metrics).build();
reporter.report();
List<String> messages = new LinkedList<>();
messages.add("Total execution time (sec): " +
Math.round((System.currentTimeMillis() - startTime) / 1000.0));
messages.add("Failures: " + failureCounter.get());
messages.add("Successful executions: " + successCounter.get());
Consumer<String> print = freonCommand.isInteractive()
? System.out::println
: LOG::info;
messages.forEach(print);
}
@Test
public void testPointsSent() throws Exception {
MetricRegistry registry = new MetricRegistry();
new BasicJvmMetrics(registry);
ScheduledReporter reporter = new ScheduledReporter(registry, "test", MetricFilter.ALL,
TimeUnit.SECONDS, TimeUnit.MILLISECONDS) {
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
Assert.assertFalse(gauges.isEmpty());
Assert.assertNotNull(gauges.get("jvm.uptime"));
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
Assert.assertNotNull(entry.getValue().getValue());
}
}
};
reporter.report();
reporter.close();
}
public static void reportTo(File directory) {
directory.mkdirs();
MetricRegistry registry = MetricsUtils.getDefaultRegistry();
ScheduledReporter csvReporter = CsvReporter.forRegistry(registry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build(directory);
csvReporter.report();
}
public static void reportTo(Logger logger) {
MetricRegistry registry = MetricsUtils.getDefaultRegistry();
ScheduledReporter consoleReporter = Slf4jReporter.forRegistry(registry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.outputTo(logger)
.build();
consoleReporter.report();
}
@Override
public void stopMetrics() {
for (ScheduledReporter r : reporters) {
r.report();
LOG.info("Stopping reporter {}", r.toString());
r.stop();
}
}
@Test
public void testExpansionFilterExclusion() throws Exception {
String json =
"{" +
"\"type\": \"datadogExpansionFiltered\"," +
"\"host\": \"test-host\"," +
"\"excludeExpansions\": [\"min\", \"max\", \"p75\", \"p95\", \"p98\", \"p99\", \"p999\"]," +
"\"transport\": {" +
"\"type\": \"http\"," +
"\"apiKey\": \"12345\"" +
"}" +
"}";
ScheduledReporter reporter = createReporter(json);
// Create a representative type.
Histogram histogram = _metricRegistry.histogram("test.histogram");
histogram.update(1);
histogram.update(2);
histogram.update(3);
reporter.report();
// Verify only the desired metrics were sent. Notably min, max, and the nth percentiles should be absent.
verify(_request).addGauge(argThat(hasGauge("test.histogram.count", 3)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.mean", 2)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.median", 2)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.stddev", 1.0)));
// Send was called exactly once
verify(_request).send();
verifyNoMoreInteractions(_request);
}
public static void main(String[] args) {
InfluxDbReporter influxDbReporter = null;
ScheduledReporter consoleReporter = null;
Timer.Context context = null;
try {
final MetricRegistry registry = new MetricRegistry();
consoleReporter = startConsoleReporter(registry);
influxDbReporter = startInfluxDbReporter(registry, GetHttpSender());
final Meter myMeter = registry.meter(MetricRegistry.name(SendToLocalInfluxDB.class, "testMetric"));
final Timer myTimer = registry.timer("testTimer");
context = myTimer.time();
for (int i = 0; i < 5000; i++) {
myMeter.mark();
myMeter.mark(Math.round(Math.random() * 100.0));
Thread.sleep(2000);
}
} catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
} finally {
if (context != null) {
context.stop();
}
if (influxDbReporter != null) {
influxDbReporter.report();
influxDbReporter.stop();
}
if (consoleReporter != null) {
consoleReporter.report();
consoleReporter.stop();
}
System.out.println("Finished");
}
}
/**
* Make sure that a correctly configured service provides a reporter for the matching configuration, and
* actually reports to the correct address.
*/
@Test
public void testCreateReporterUsesCorrectSender() throws Exception {
testedService = new TestableGraphiteMetricReporterService();
runner.addControllerService(SERVICE_IDENTIFIER, testedService);
setServiceProperties(TEST_HOST, TEST_PORT, TEST_CHARSET, METRIC_NAMES_PREFIX);
runner.enableControllerService(testedService);
ScheduledReporter createdReporter = testedService.createReporter(metricRegistryStub);
createdReporter.report();
String expectedMetricName = MetricRegistry.name(METRIC_NAMES_PREFIX, TEST_METRIC_NAME);
verify(graphiteSenderMock).send(eq(expectedMetricName), eq(String.valueOf(TEST_METRIC_VALUE)), anyLong());
}
@Test
public void testExpansionFilterInclusion() throws Exception {
String json =
"{" +
"\"type\": \"datadogExpansionFiltered\"," +
"\"host\": \"test-host\"," +
"\"includeExpansions\": [\"count\", \"min\", \"max\", \"p95\"]," +
"\"transport\": {" +
"\"type\": \"http\"," +
"\"apiKey\": \"12345\"" +
"}" +
"}";
ScheduledReporter reporter = createReporter(json);
// Create some metrics for each major type
Counter counter = _metricRegistry.counter("test.counter");
counter.inc(10);
Histogram histogram = _metricRegistry.histogram("test.histogram");
histogram.update(1);
histogram.update(2);
histogram.update(3);
Meter meter = _metricRegistry.meter("test.meter");
meter.mark(100);
Timer timer = _metricRegistry.timer("test.timer");
timer.update(1, TimeUnit.SECONDS);
timer.update(2, TimeUnit.SECONDS);
timer.update(3, TimeUnit.SECONDS);
_metricRegistry.register("test.gauge", new Gauge<Integer>() {
@Override
public Integer getValue() {
return 50;
}
});
reporter.report();
// Verify only the desired metrics were sent
verify(_request).addGauge(argThat(hasGauge("test.counter", 10)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.count", 3)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.min", 1)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.max", 3)));
verify(_request).addGauge(argThat(hasGauge("test.histogram.p95", 3.0)));
verify(_request).addGauge(argThat(hasGauge("test.timer.count", 3)));
verify(_request).addGauge(argThat(hasGauge("test.timer.min", 1000f)));
verify(_request).addGauge(argThat(hasGauge("test.timer.max", 3000f)));
verify(_request).addGauge(argThat(hasGauge("test.timer.p95", 3000f)));
verify(_request).addGauge(argThat(hasGauge("test.meter.count", 100)));
verify(_request).addGauge(argThat(hasGauge("test.gauge", 50)));
// Send was called exactly once
verify(_request).send();
verifyNoMoreInteractions(_request);
}
@Test
public void verifySendingToCloudWatch() throws Exception {
CloudWatchReporterFactory factory = new CloudWatchReporterFactory();
MetricRegistry registry = new MetricRegistry();
Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));
AmazonCloudWatchAsync mockClient = mock(AmazonCloudWatchAsync.class);
final Future<Void> mockFuture = mock(Future.class);
when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenReturn(mockFuture);
when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenAnswer(new Answer<Future>() {
@Override
public Future answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
if (args.length > 0 && args[0] != null) {
PutMetricDataRequest req = (PutMetricDataRequest) args[0];
assertEquals(req.getNamespace(), "myspace");
for (MetricDatum datum : req.getMetricData()) {
System.out.println(datum.toString());
assertTrue(datum.toString().contains("env"));
}
}
return mockFuture;
}
});
factory.setClient(mockClient);
factory.setAwsAccessKeyId("fakeKey");
factory.setAwsSecretKey("fakeSecret");
factory.setNamespace("myspace");
factory.setGlobalDimensions(Lists.newArrayList("env=dev"));
ScheduledReporter reporter = factory.build(registry);
for (int i = 0; i < 200; i++) {
counter.inc();
}
reporter.report();
verify(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class)), times(1));
}