com.codahale.metrics.ScheduledReporter Java Examples

The following examples show how to use com.codahale.metrics.ScheduledReporter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicJvmMetrisTest.java    From signalfx-java with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: InfluxdbReporter.java    From jboot with Apache License 2.0 6 votes vote down vote up
@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);
    }
 
Example #3
Source File: MetricsConfiguration.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: BaseFreonGenerator.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: DatadogMetricFilterTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: PrometheusReporterFactory.java    From dropwizard-prometheus with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #7
Source File: CodahaleMetricsProvider.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #8
Source File: CodahaleMetricsProvider.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #9
Source File: CodahaleMetricsProvider.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: CodahaleMetricsProvider.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Override
public void stopMetrics() {
    for (ScheduledReporter r : reporters) {
        r.report();
        LOG.info("Stopping reporter {}", r.toString());
        r.stop();
    }
}
 
Example #11
Source File: CodahaleMetricsProvider.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #12
Source File: GraphiteMetrics.java    From replicator with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #13
Source File: DatadogMetricFilterTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #14
Source File: DatadogExpansionFilteredReporterFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #15
Source File: SendToLocalInfluxDB.java    From dropwizard-metrics-influxdb with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example #16
Source File: WavefrontMetricsReporterFactory.java    From dropwizard-wavefront with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #17
Source File: DropwizardFlinkHistogramWrapperTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledReporter getReporter(MetricConfig config) {
	scheduledReporter = new TestingScheduledReporter(
		registry,
		getClass().getName(),
		null,
		TimeUnit.MILLISECONDS,
		TimeUnit.MILLISECONDS);

	return scheduledReporter;
}
 
Example #18
Source File: ScheduledDropwizardReporterTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #19
Source File: SiddhiStatisticsManager.java    From siddhi with Apache License 2.0 5 votes vote down vote up
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");
        }
    }
}
 
Example #20
Source File: ConsoleEventReporterFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #21
Source File: Metric.java    From esigate with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: GraphiteMetricReporterServiceTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example #23
Source File: ScheduledDropwizardReporterTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #24
Source File: GraphiteScheduledReporterFactory.java    From circus-train with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: Reporter.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #26
Source File: Reporter.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #27
Source File: MetricsConfiguration.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #28
Source File: DropwizardFlinkHistogramWrapperTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledReporter getReporter(MetricConfig config) {
	scheduledReporter = new TestingScheduledReporter(
		registry,
		getClass().getName(),
		null,
		TimeUnit.MILLISECONDS,
		TimeUnit.MILLISECONDS);

	return scheduledReporter;
}
 
Example #29
Source File: MetricsConfiguration.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: ScheduledDropwizardReporterTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@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"));
}