下面列出了怎么用com.codahale.metrics.ScheduledReporter的API类实例代码及写法,或者点击链接到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);
}
@Bean
@ConditionalOnProperty(prefix = "metrics.influxdb", name = "enabled", havingValue = "true")
ScheduledReporter influxdbReporter(InfluxdbProperties influxdbProperties, MetricRegistry metricRegistry)
throws Exception {
final InfluxDbSender influxDbSender = new InfluxDbHttpSender(
influxdbProperties.getProtocol(),
influxdbProperties.getHost(),
influxdbProperties.getPort(),
influxdbProperties.getDatabase(),
influxdbProperties.getAuth(),
TimeUnit.SECONDS,
influxdbProperties.getConnectTimeout(),
influxdbProperties.getReadTimeout(),
influxdbProperties.getPrefix());
final Map<String, String> tags = ObjectUtils.defaultIfNull(
influxdbProperties.getTags(),
Collections.emptyMap()
);
final ScheduledReporter reporter = InfluxDbReporter
.forRegistry(metricRegistry)
.withTags(tags)
.build(influxDbSender);
reporter.start(influxdbProperties.getInterval(), TimeUnit.SECONDS);
return reporter;
}
@Override
public void report(MetricRegistry metricRegistry) {
JbootMetricInfluxdbReporterConfig config = Jboot.config(JbootMetricInfluxdbReporterConfig.class);
final ScheduledReporter reporter = metrics_influxdb.InfluxdbReporter.forRegistry(metricRegistry)
.protocol(new HttpInfluxdbProtocol("http"
, config.getHost()
, config.getPort()
, config.getUser()
, config.getPassword()
, config.getDbName()))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.skipIdleMetrics(false)
// .tag("cluster", config.getTagCluster())
// .tag("client", config.getTagClient())
// .tag("server", serverIP)
// .transformer(new CategoriesMetricMeasurementTransformer("module", "artifact"))
.build();
reporter.start(10, TimeUnit.SECONDS);
}
private ScheduledReporter createReporter(String json)
throws Exception {
ObjectMapper objectMapper = Jackson.newObjectMapper();
ReporterFactory reporterFactory = objectMapper.readValue(json, ReporterFactory.class);
assertTrue(reporterFactory instanceof DatadogExpansionFilteredReporterFactory);
DatadogExpansionFilteredReporterFactory datadogReporterFactory = (DatadogExpansionFilteredReporterFactory) reporterFactory;
// Replace the transport with our own mock for testing
Transport transport = mock(Transport.class);
when(transport.prepare()).thenReturn(_request);
AbstractTransportFactory transportFactory = mock(AbstractTransportFactory.class);
when(transportFactory.build()).thenReturn(transport);
datadogReporterFactory.setTransport(transportFactory);
// Build the reporter
return datadogReporterFactory.build(_metricRegistry);
}
@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();
}
@Override
public ScheduledReporter getReporter(MetricConfig config) {
scheduledReporter = new TestingScheduledReporter(
registry,
getClass().getName(),
null,
TimeUnit.MILLISECONDS,
TimeUnit.MILLISECONDS);
return scheduledReporter;
}
@Test
public void testInvalidCharacterReplacement() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ScheduledDropwizardReporter reporter = new ScheduledDropwizardReporter() {
@Override
public ScheduledReporter getReporter(MetricConfig config) {
return null;
}
};
assertEquals("abc", reporter.filterCharacters("abc"));
assertEquals("a--b-c-", reporter.filterCharacters("a..b.c."));
assertEquals("ab-c", reporter.filterCharacters("a\"b.c"));
}
@Override
public ScheduledReporter getReporter(MetricConfig config) {
scheduledReporter = new TestingScheduledReporter(
registry,
getClass().getName(),
null,
TimeUnit.MILLISECONDS,
TimeUnit.MILLISECONDS);
return scheduledReporter;
}
@Test
public void testInvalidCharacterReplacement() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ScheduledDropwizardReporter reporter = new ScheduledDropwizardReporter() {
@Override
public ScheduledReporter getReporter(MetricConfig config) {
return null;
}
};
assertEquals("abc", reporter.filterCharacters("abc"));
assertEquals("a--b-c-", reporter.filterCharacters("a..b.c."));
assertEquals("ab-c", reporter.filterCharacters("a\"b.c"));
}
@Bean
@ConditionalOnProperty(prefix = "metrics.graphite", name = "enabled", havingValue = "true")
ScheduledReporter graphiteReporter(GraphiteProperties graphiteProperties, MetricRegistry metricRegistry) {
final Graphite graphite = new Graphite(graphiteProperties.getHost(), graphiteProperties.getPort());
final ScheduledReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
.prefixedWith(graphiteProperties.getPrefix())
.build(graphite);
reporter.start(graphiteProperties.getInterval(), TimeUnit.SECONDS);
return reporter;
}
@Bean
@ConditionalOnProperty(prefix = "metrics.console", name = "enabled", havingValue = "true")
ScheduledReporter consoleReporter(ConsoleProperties consoleProperties, MetricRegistry metricRegistry) {
final ScheduledReporter reporter = ConsoleReporter.forRegistry(metricRegistry).build();
reporter.start(consoleProperties.getInterval(), TimeUnit.SECONDS);
return reporter;
}
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 ScheduledReporter newInstance(String qualifiedReplicaName) {
InetSocketAddress address = new InetSocketAddressFactory().newInstance(graphiteHost);
Graphite graphite = new Graphite(address);
String prefix = DotJoiner.join(graphitePrefix, qualifiedReplicaName);
return GraphiteReporter.forRegistry(runningMetricRegistry).prefixedWith(prefix).build(graphite);
}
@Override
public ScheduledReporter build(MetricRegistry registry) {
final Pushgateway pushgateway = new Pushgateway(url, job);
final PrometheusReporter reporter = PrometheusReporter.forRegistry(registry)
.prefixedWith(prefix)
.filter(getFilter())
.build(pushgateway);
return reporter;
}
public CodahaleMetricsProvider(CodahaleMetricsConfig conf) throws IOException {
metricsOutputFrequencyInSecs = conf.getOutputFreqInSecs();
int reporterCount = 0;
for (Reporter reporter : conf.getReporters()) {
ScheduledReporter codahaleReporter = null;
switch (reporter) {
case CONSOLE:
codahaleReporter = createAndGetConfiguredConsoleReporter();
break;
case GRAPHITE:
codahaleReporter = createAndGetConfiguredGraphiteReporter(conf.getPrefix(),
conf.getGraphiteHostConfig());
break;
case CSV:
codahaleReporter = createAndGetConfiguredCSVReporter(conf.getPrefix(),
conf.getCsvDir());
break;
case SLF4J:
codahaleReporter = createAndGetConfiguredSlf4jReporter(conf.getSlf4jLogger());
break;
}
if (codahaleReporter != null) {
reporters.add(codahaleReporter);
reporterCount++;
}
}
if (reporterCount == 0) {
LOG.warn("No metric reporters found, so metrics won't be available");
}
startMetrics();
}
@Override
public void startMetrics() {
for (ScheduledReporter r : reporters) {
LOG.info("Starting metrics reporter {} reporting every {} Secs",
r.getClass().getCanonicalName(), metricsOutputFrequencyInSecs);
r.start(metricsOutputFrequencyInSecs, TimeUnit.SECONDS);
}
}
@Override
public void stopMetrics() {
for (ScheduledReporter r : reporters) {
r.report();
LOG.info("Stopping reporter {}", r.toString());
r.stop();
}
}
private ScheduledReporter createAndGetConfiguredGraphiteReporter(String prefix, String graphiteHost) {
LOG.info("Configuring Graphite reporter. Sendig data to host:port {}", graphiteHost);
HostAndPort addr = HostAndPort.fromString(graphiteHost);
final Graphite graphite = new Graphite(
new InetSocketAddress(addr.getHostText(), addr.getPort()));
return GraphiteReporter.forRegistry(metrics)
.prefixedWith(prefix)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
}
private ScheduledReporter createAndGetConfiguredSlf4jReporter(String slf4jLogger) {
LOG.info("Configuring stats with SLF4J with logger {}", slf4jLogger);
return Slf4jReporter.forRegistry(metrics)
.outputTo(LoggerFactory.getLogger(slf4jLogger))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
}
@Override
protected ScheduledReporter getReporter(Map<String, Object> configuration, MetricRegistry registry) {
Object namespace = configuration.get(Configuration.GRAPHITE_NAMESPACE);
Object hostname = configuration.get(Configuration.GRAPHITE_HOSTNAME);
Object port = configuration.get(Configuration.GRAPHITE_PORT);
Objects.requireNonNull(namespace, String.format("Configuration required: %s", Configuration.GRAPHITE_NAMESPACE));
Objects.requireNonNull(hostname, String.format("Configuration required: %s", Configuration.GRAPHITE_HOSTNAME));
Objects.requireNonNull(port, String.format("Configuration required: %s", Configuration.GRAPHITE_PORT));
registry.register(MetricRegistry.name("jvm", "gc"), new GarbageCollectorMetricSet());
registry.register(MetricRegistry.name("jvm", "threads"), new ThreadStatesGaugeSet());
registry.register(MetricRegistry.name("jvm", "classes"), new ClassLoadingGaugeSet());
registry.register(MetricRegistry.name("jvm", "fd"), new FileDescriptorRatioGauge());
registry.register(MetricRegistry.name("jvm", "memory"), new MemoryUsageGaugeSet());
ScheduledReporter reporter = GraphiteReporter
.forRegistry(registry)
.prefixedWith(namespace.toString())
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.SECONDS)
.build(new Graphite(new InetSocketAddress(hostname.toString(), Integer.parseInt(port.toString()))));
reporter.start(1L, TimeUnit.MINUTES);
return reporter;
}
@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 ScheduledReporter build(MetricRegistry registry) {
return DatadogReporter.forRegistry(registry)
.withTransport(_transport.build())
.withHost(_host)
.withTags(_tags)
.filter(getFilter())
.withExpansions(getExpansions())
.convertDurationsTo(getDurationUnit())
.convertRatesTo(getRateUnit())
.build();
}
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");
}
}
@Override
public ScheduledReporter build(MetricRegistry metricRegistry) {
try {
return WavefrontMetricsReporter.forRegistry(metricRegistry)
.withHostname(hostname)
.withToken(token)
.convertRatesTo(getRateUnit())
.convertDurationsTo(getDurationUnit())
.filter(getFilter())
.build();
} catch (UnknownHostException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public ScheduledReporter getReporter(MetricConfig config) {
scheduledReporter = new TestingScheduledReporter(
registry,
getClass().getName(),
null,
TimeUnit.MILLISECONDS,
TimeUnit.MILLISECONDS);
return scheduledReporter;
}
@Test
public void testInvalidCharacterReplacement() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ScheduledDropwizardReporter reporter = new ScheduledDropwizardReporter() {
@Override
public ScheduledReporter getReporter(MetricConfig config) {
return null;
}
};
assertEquals("abc", reporter.filterCharacters("abc"));
assertEquals("a--b-c-", reporter.filterCharacters("a..b.c."));
assertEquals("ab-c", reporter.filterCharacters("a\"b.c"));
}
public void stopReporting() {
if (reporter != null) {
if (reporter instanceof ScheduledReporter) {
((ScheduledReporter) reporter).stop();
} else if (reporter instanceof JmxReporter) {
((JmxReporter) reporter).stop();
} else {
throw new UnsupportedOperationException("Only 'ConsoleReporter' and 'JmxReporter' is supported," +
" Reporter type '" + reporter.getClass().getName() + "' is not supported");
}
}
}
@Override
public ScheduledReporter newScheduledReporter(MetricRegistry registry, Properties properties) throws IOException {
try {
return OutputStreamEventReporter.forContext(MetricContext.class.cast(registry)).build();
} catch (ClassCastException cce) {
throw new IOException(cce);
}
}
@Override
public void init(Driver d, Properties properties) {
this.driver = d;
LOG.debug("Initialize Metric");
driver.getEventManager().register(EventManager.EVENT_PROXY_POST, this);
driver.getEventManager().register(EventManager.EVENT_FETCH_POST, this);
ScheduledReporter reporter =
Slf4jReporter.forRegistry(this.metric).outputTo(LOG).convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS).build();
reporter.start(PARAM_METRIC_PERIOD.getValue(properties), TimeUnit.SECONDS);
}