com.codahale.metrics.Meter Java Examples

The following examples show how to use com.codahale.metrics.Meter. 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: MetricsModule.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Meter meter, JsonGenerator json,
                      SerializerProvider provider) throws IOException {
    json.writeStartObject();
    json.writeNumberField("count", meter.getCount());
    json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() *
                                      this.rateFactor);
    json.writeNumberField("m1_rate", meter.getOneMinuteRate() *
                                     this.rateFactor);
    json.writeNumberField("m5_rate", meter.getFiveMinuteRate() *
                                     this.rateFactor);
    json.writeNumberField("mean_rate", meter.getMeanRate() *
                                       this.rateFactor);
    json.writeStringField("units", this.rateUnit);
    json.writeEndObject();
}
 
Example #2
Source File: SignalFxAwareCodahaleMetricsCollectorTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "null",
    "0",
    "1",
    "2"
}, splitBy = "\\|")
@Test
public void getNamedMeter_with_iterable_dimensions_creates_dimensioned_meter_using_sfx_mechanisms(
    Integer numDimensions
) {
    // given
    String meterName = UUID.randomUUID().toString();
    List<Pair<String, String>> iterableDims = generateIterableDimensions(numDimensions);

    // when
    Meter result = sfxImpl.getNamedMeter(meterName, iterableDims);

    // then
    verifyMetricCreation(MetricBuilder.METERS, meterTaggerMock, meterName, iterableDims, meterMock, result);
}
 
Example #3
Source File: DynamicMetricsManager.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Get a metric object based on its class. Note that codahale MetricRegistry
 * does a getOrAdd behind of scene of counter()/meter()/histogram(), etc.
 * @param name fully-qualified name of the metric
 * @param clazz class object of the metric
 * @param <T> metric type
 * @return metric object
 */
@SuppressWarnings("unchecked")
private <T extends Metric> T getMetric(String name, Class<T> clazz) {
  if (clazz.equals(Counter.class)) {
    return (T) _metricRegistry.counter(name);
  } else if (clazz.equals(Meter.class)) {
    return (T) _metricRegistry.meter(name);
  } else if (clazz.equals(Histogram.class)) {
    return (T) _metricRegistry.histogram(name);
  } else if (clazz.equals(Gauge.class)) {
    return (T) new ResettableGauge<>();
  } else if (clazz.equals(Timer.class)) {
    return (T) new Timer();
  } else {
    throw new IllegalArgumentException("Invalid metric type: " + clazz);
  }
}
 
Example #4
Source File: InstrumentedInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
@Test
public void noAnnotation() {

    Timer timer = testMetricRegistry.timer("timed");
    Meter meter = testMetricRegistry.meter("metered");
    when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
    when(mockMetricRegistry.meter(anyString())).thenReturn(meter);

    long oldtimervalue = timer.getCount();
    long oldmetervalue = meter.getCount();

    Invoker invoker = invokerBuilder.create(instrumentedService, new FooInvoker());
    this.setTargetMethod(exchange, "foo"); // simulate CXF behavior

    Object result = invoker.invoke(exchange, null);
    assertEquals("fooReturn", result);

    assertThat(timer.getCount(), is(oldtimervalue));
    assertThat(meter.getCount(), is(oldmetervalue));
}
 
Example #5
Source File: DropWizardMetricsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void collect_Meter() {
  Meter getRequests = metricRegistry.meter("get_requests");
  getRequests.mark();
  getRequests.mark();

  ArrayList<Metric> metrics = new ArrayList<>(dropWizardMetrics.getMetrics());
  assertThat(metrics.size()).isEqualTo(1);

  assertThat(metrics.get(0).getMetricDescriptor())
      .isEqualTo(
          MetricDescriptor.create(
              "codahale_get_requests_meter",
              "Collected from codahale (metric=get_requests, "
                  + "type=com.codahale.metrics.Meter)",
              DEFAULT_UNIT,
              Type.CUMULATIVE_INT64,
              Collections.<LabelKey>emptyList()));
  assertThat(metrics.get(0).getTimeSeriesList().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getLabelValues().size()).isEqualTo(0);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().get(0).getValue())
      .isEqualTo(Value.longValue(2));
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getStartTimestamp()).isNotNull();
}
 
Example #6
Source File: ResultSetTest.java    From metrics-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void testResultSetLife() throws SQLException {
    // Act
    Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select * from METRICS_TEST");
    while(resultSet.next()) {
        int id = resultSet.getInt("ID");
        String text = resultSet.getString("TEXT");
        Timestamp timestamp = resultSet.getTimestamp("CREATED");
    }
    H2DbUtil.close(resultSet, statement, connection);
    // Assert
    assertNotNull(connection);
    assertTrue(Proxy.isProxyClass(resultSet.getClass()));
    Timer timer = metricRegistry.getTimers().get("java.sql.ResultSet.[select * from metrics_test]");
    assertNotNull(timer);
    assertEquals(1L, timer.getCount());
    Meter meter = metricRegistry.meter("java.sql.ResultSet.[select * from metrics_test].rows");
    assertNotNull(meter);
    assertEquals(11L, meter.getCount());
}
 
Example #7
Source File: MorphlineTest.java    From kite with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadLine() throws Exception {
  String threeLines = "first\nsecond\nthird";
  byte[] in = threeLines.getBytes("UTF-8");
  morphline = createMorphline("test-morphlines/readLine"); // uses ignoreFirstLine : true
  Record record = new Record();
  record.put(Fields.ATTACHMENT_BODY, in);
  processAndVerifySuccess(record, 
      ImmutableMultimap.of(Fields.MESSAGE, "second"), 
      ImmutableMultimap.of(Fields.MESSAGE, "third")
  );
  
  // verify counters
  boolean foundCounter = false;
  for (Entry<String, Meter> entry : morphContext.getMetricRegistry().getMeters().entrySet()) {
    if (entry.getKey().equals("morphline.readLine." + Metrics.NUM_RECORDS)) {
      assertEquals(2, entry.getValue().getCount());
      foundCounter = true;
    }
  }
  assertTrue(foundCounter);
}
 
Example #8
Source File: InfluxDbReporterTest.java    From dropwizard-metrics-influxdb with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSkipIdleMetrics() throws Exception {
    when(influxDb.hasSeriesData()).thenReturn(true);

    final Meter meter = mock(Meter.class);
    when(meter.getCount()).thenReturn(1L);
    when(meter.getOneMinuteRate()).thenReturn(2.0);
    when(meter.getFiveMinuteRate()).thenReturn(3.0);
    when(meter.getFifteenMinuteRate()).thenReturn(4.0);
    when(meter.getMeanRate()).thenReturn(5.0);

    InfluxDbReporter skippingReporter = InfluxDbReporter
        .forRegistry(registry)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .filter(MetricFilter.ALL)
        .withTags(globalTags)
        .skipIdleMetrics(true)
        .build(influxDb);

    skippingReporter.report(this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), this.map("meter", meter), this.<Timer>map());
    skippingReporter.report(this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), this.map("meter", meter), this.<Timer>map());

    verify(influxDb, times(1)).appendPoints(Mockito.any(InfluxDbPoint.class));
}
 
Example #9
Source File: MeteredOutputStreamTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

  Meter meter = new Meter();
  MeteredOutputStream mos = MeteredOutputStream.builder().out(outputStream).meter(meter).updateFrequency(1).build();

  MyOutputStream duplicated = new MyOutputStream(mos);
  DataOutputStream dos = new DataOutputStream(duplicated);

  dos.write("abcde".getBytes(Charsets.UTF_8));

  Assert.assertEquals(outputStream.toString(Charsets.UTF_8.name()), "aabbccddee");
  Optional<MeteredOutputStream> meteredOutputStream = MeteredOutputStream.findWrappedMeteredOutputStream(dos);
  Assert.assertEquals(meteredOutputStream.get(), mos);
  Assert.assertEquals(meteredOutputStream.get().getBytesProcessedMeter().getCount(), 10);
}
 
Example #10
Source File: TopologyEventsMetricsCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Prints an Event Metric.
 *
 * @param operationStr the string with the intent operation to print
 * @param eventMetric the Event Metric to print
 */
private void printEventMetric(String operationStr,
                              EventMetric eventMetric) {
    Gauge<Long> gauge = eventMetric.lastEventTimestampGauge();
    Meter meter = eventMetric.eventRateMeter();
    TimeUnit rateUnit = TimeUnit.SECONDS;
    double rateFactor = rateUnit.toSeconds(1);

    // Print the Gauge
    print(FORMAT_GAUGE, operationStr, gauge.getValue());

    // Print the Meter
    print(FORMAT_METER, operationStr, meter.getCount(),
          meter.getMeanRate() * rateFactor,
          meter.getOneMinuteRate() * rateFactor,
          meter.getFiveMinuteRate() * rateFactor,
          meter.getFifteenMinuteRate() * rateFactor);
}
 
Example #11
Source File: TestDataObserverRunner.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleObserverRequestAlertAndMeter() {
  RulesConfigurationChangeRequest rulesConfigurationChangeRequest = createRulesConfigurationChangeRequest(true, true);
  dataObserverRunner.handleConfigurationChangeRequest(rulesConfigurationChangeRequest);
  dataObserverRunner.handleDataRulesEvaluationRequest(createProductionObserverRequest());
  Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics, AlertsUtil.getAlertGaugeName("myId"));
  Assert.assertNotNull(gauge);
  Assert.assertEquals((long) 3, ((Map<String, Object>) gauge.getValue()).get("currentValue"));
  Assert.assertNotNull(((Map<String, Object>) gauge.getValue()).get("timestamp"));

  Meter meter = MetricsConfigurator.getMeter(metrics, AlertsUtil.getUserMetricName("myId"));
  Assert.assertNotNull(meter);
  Assert.assertEquals(3, meter.getCount());
}
 
Example #12
Source File: GraphiteReporter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
protected void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
    SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
    Map<String, Object> tags) {

  String prefix = getMetricNamePrefix(tags);
  long timestamp = System.currentTimeMillis() / 1000l;

  try {
    for (Map.Entry<String, Gauge> gauge : gauges.entrySet()) {
      reportGauge(prefix, gauge.getKey(), gauge.getValue(), timestamp);
    }

    for (Map.Entry<String, Counter> counter : counters.entrySet()) {
      reportCounter(prefix, counter.getKey(), counter.getValue(), timestamp);
    }

    for (Map.Entry<String, Histogram> histogram : histograms.entrySet()) {
      reportHistogram(prefix, histogram.getKey(), histogram.getValue(), timestamp);
    }

    for (Map.Entry<String, Meter> meter : meters.entrySet()) {
      reportMetered(prefix, meter.getKey(), meter.getValue(), timestamp);
    }

    for (Map.Entry<String, Timer> timer : timers.entrySet()) {
      reportTimer(prefix, timer.getKey(), timer.getValue(), timestamp);
    }

    this.graphitePusher.flush();

  } catch (IOException ioe) {
    LOGGER.error("Error sending metrics to Graphite", ioe);
    try {
      this.graphitePusher.close();
    } catch (IOException innerIoe) {
      LOGGER.error("Error closing the Graphite sender", innerIoe);
    }
  }
}
 
Example #13
Source File: ResponseMetricCollectorTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLogExceptionOnCompletion() {
	when(context.getAttribute(ResponseMetricCollector.SUCCESSFUL)).thenReturn(null);
	when(context.getApplication()).thenReturn(application);
	
	Meter meter = mock(Meter.class);
	when(metricRegistry.meter("test." + ResponseMetricCollector.EXCEPTIONS)).thenReturn(meter);
	collector.onComplete(context);
	verify(meter).mark();
}
 
Example #14
Source File: GraphiteReporter.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
public void report(SortedMap<String, Gauge> gauges,
                   SortedMap<String, Counter> counters,
                   SortedMap<String, Histogram> histograms,
                   SortedMap<String, Meter> meters,
                   SortedMap<String, Timer> timers) {
    long timestamp = clock.getTime() / 1000;

    try {

        initConnection();
        gauges.forEach((name, gauge) ->
                doReport(name, gauge, timestamp, this::reportGauge));

        counters.forEach((name, counter) ->
                doReport(name, counter, timestamp, this::reportCounter));

        histograms.forEach((name, histogram) ->
                doReport(name, histogram, timestamp, this::reportHistogram));

        meters.forEach((name, meter) ->
                doReport(name, meter, timestamp, this::reportMetered));

        timers.forEach((name, timer) ->
                doReport(name, timer, timestamp, this::reportTimer));

        graphite.flush();
    } catch (Exception e) {
        LOGGER.error("Error reporting metrics" + e.getMessage(), e);
    } finally {
        try {
            graphite.close();
        } catch (IOException e1) {
            LOGGER.warn("Error closing Graphite", graphite, e1);
        }
    }
}
 
Example #15
Source File: CustomMetricsReporter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private List<Metric> convert(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
                             SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
                             SortedMap<String, Timer> timers) {
    long timestamp = System.currentTimeMillis();
    boolean metricQuantiles = customMetricsConfig.metricQuantiles();

    return Stream.of(new GaugeConverter().convert(gauges, timestamp), 
              new CounterConverter().convert(counters, timestamp),
              new HistogramConverter(metricQuantiles).convert(histograms, timestamp), 
              new MeterConverter(metricQuantiles).convert(meters, timestamp),
              new TimerConverter(metricQuantiles).convert(timers, timestamp))
    .flatMap(Collection::stream)
    .collect(Collectors.toList());
}
 
Example #16
Source File: GraphManagerShardConsistencyIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private ReadWorker( final GraphManagerFactory factory, final EdgeGenerator generator, final long writeCount,
                    final Meter readMeter ) {
    this.factory = factory;
    this.generator = generator;
    this.writeCount = writeCount;
    this.readMeter = readMeter;
}
 
Example #17
Source File: MetricsConfigurator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static Meter createMeter(MetricRegistry metrics, String name, final String pipelineName, final String pipelineRev) {
  return create(
    metrics,
    new ExtendedMeter(),
    metricName(name, METER_SUFFIX),
    pipelineName,
    pipelineRev
  );
}
 
Example #18
Source File: MqMetricReporter.java    From pmq with Apache License 2.0 5 votes vote down vote up
private Set<Metric> buildMeters(String name, Meter meter, long timestamp, Map<String, String> tags) {
    final MetricsCollector collector = MetricsCollector.createNew(name, tags, timestamp);
    if (getChangeCount(name, meter.getCount()) == 0) {
        return Collections.emptySet();
    }
    return collector.addMetric("count", meter.getCount())
            // convert rate
            .addMetric("mean_rate", convertRate(meter.getMeanRate()))
            .addMetric("m1", convertRate(meter.getOneMinuteRate()))
            .addMetric("m5", convertRate(meter.getFiveMinuteRate()))
            .addMetric("m15", convertRate(meter.getFifteenMinuteRate()))
            .build();
}
 
Example #19
Source File: HttpErrorStatusMetricsTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void metricsArePreRegistered() {
    assertThat(registry.getMeters().get("styx.errors"), is(instanceOf(Meter.class)));
    assertThat(registry.getMeters().get("styx.errors").getCount(), is(0L));

    assertThat(registry.getCounters().get("styx.response.status.200"), is(instanceOf(Counter.class)));
    assertThat(registry.getCounters().get("styx.response.status.200").getCount(), is(0L));

    assertThat(registry.getCounters().get("styx.exception.java_lang_Exception"), is(instanceOf(Counter.class)));
    assertThat(registry.getCounters().get("styx.exception.java_lang_Exception").getCount(), is(0L));
}
 
Example #20
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public void metered(@NotNull Runnable r, @NotNull String meterName, long events) {
    final Meter meter = getNamedMeter(meterName);
    try {
        r.run();
    }
    finally {
        meter.mark(events);
    }
}
 
Example #21
Source File: OriginMetricsTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void response403ForbiddenUpdatesClientErrorOnly() {
    originMetrics.responseWithStatusCode(403);

    Meter meter = rootMetricRegistry.meter(name(APP_METRIC_PREFIX, "requests.response.status.403"));
    assertThat(meter.getCount(), is(1L));

    meter = rootMetricRegistry.meter(name(ORIGIN_METRIC_PREFIX, "requests.response.status.403"));
    assertThat(meter.getCount(), is(1L));

    assertThat(rootMetricRegistry, is(hasNotReceivedUpdatesExcept(
            name(APP_METRIC_PREFIX, "requests.response.status.403"),
            name(ORIGIN_METRIC_PREFIX, "requests.response.status.403"))));
}
 
Example #22
Source File: MeteredMethodBeanTest.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void callMeteredMethodOnce() {
    assertThat("Meter is not registered correctly", registry.getMeters(), hasKey(METER_NAME));
    Meter meter = registry.getMeters().get(METER_NAME);

    // Call the metered method and assert it's been marked
    bean.meteredMethod();

    // Make sure that the meter has been marked
    assertThat("Timer count is incorrect", meter.getCount(), is(equalTo(METER_COUNT.incrementAndGet())));
}
 
Example #23
Source File: TestMetricsEnabledWrapperStream.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  testDir = new File("target", UUID.randomUUID().toString());
  testDir.mkdirs();
  FileRefTestUtil.writePredefinedTextToFile(testDir);
  gauge = new MapGauge();
  context = Mockito.mock(Stage.Context.class);
  when(context.createGauge(Mockito.any(), Mockito.any())).thenReturn(gauge);
  when(context.getGauge(Mockito.any())).thenReturn(gauge);
  when(context.getMeter(Mockito.any())).thenReturn(new Meter());
  when(context.getRunnerId()).thenReturn(0);
}
 
Example #24
Source File: OriginMetricsTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void response204NoContentUpdatesSuccessfulMeterOnly() {
    originMetrics.responseWithStatusCode(204);

    Meter meter = rootMetricRegistry.meter(name(APP_METRIC_PREFIX, "requests.response.status.204"));
    assertThat(meter.getCount(), is(1L));

    meter = rootMetricRegistry.meter(name(ORIGIN_METRIC_PREFIX, "requests.response.status.204"));
    assertThat(meter.getCount(), is(1L));

    assertThat(rootMetricRegistry, is(hasNotReceivedUpdatesExcept(
            name(APP_METRIC_PREFIX, "requests.response.status.204"),
            name(ORIGIN_METRIC_PREFIX, "requests.response.status.204"))));
}
 
Example #25
Source File: MetricsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests GetAllMetrics method.
 */
@Test
public void testGetAllMetrics() {
    Counter onosCounter = new Counter();
    onosCounter.inc();

    Meter onosMeter = new Meter();
    onosMeter.mark();

    Timer onosTimer = new Timer();
    onosTimer.update(1, TimeUnit.MILLISECONDS);

    ImmutableMap<String, Metric> metrics =
            new ImmutableMap.Builder<String, Metric>()
                    .put("onosCounter", onosCounter)
                    .put("onosMeter", onosMeter)
                    .put("onosTimer", onosTimer)
                    .build();

    expect(mockMetricsService.getMetrics())
            .andReturn(metrics)
            .anyTimes();

    replay(mockMetricsService);

    WebTarget wt = target();
    String response = wt.path("metrics").request().get(String.class);
    assertThat(response, containsString("{\"metrics\":["));

    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    JsonArray jsonMetrics = result.get("metrics").asArray();
    assertThat(jsonMetrics, notNullValue());
    assertThat(jsonMetrics.size(), is(3));

    assertTrue(matchesMetric(metrics.get("onosCounter")).matchesSafely(jsonMetrics.get(0).asObject()));
    assertTrue(matchesMetric(metrics.get("onosMeter")).matchesSafely(jsonMetrics.get(1).asObject()));
    assertTrue(matchesMetric(metrics.get("onosTimer")).matchesSafely(jsonMetrics.get(2).asObject()));
}
 
Example #26
Source File: TrainingFetcher.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
TrainingFetcher(MetricSampler metricSampler,
                Cluster cluster,
                SampleStore sampleStore,
                Set<TopicPartition> assignedPartitions,
                long startTimeMs,
                long endTimeMs,
                MetricDef metricDef,
                Timer fetchTimer,
                Meter fetchFailureRate) {
  super(metricSampler, cluster, sampleStore, assignedPartitions, startTimeMs, endTimeMs, metricDef, fetchTimer, fetchFailureRate, SAMPLING_MODE);
}
 
Example #27
Source File: MetricsHandler.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Response response = routeContext.getResponse().noCache().text();

    try (BufferedWriter writer = new BufferedWriter(response.getWriter())) {
        SortedMap<String, Gauge> gauges = metricRegistry.getGauges();
        if (gauges.size() > 0) {
            writeGauges(gauges, writer);
            writer.newLine();
        }

        SortedMap<String, Counter> counters = metricRegistry.getCounters();
        if (counters.size() > 0) {
            writeCounters(counters, writer);
            writer.newLine();
        }

        SortedMap<String, Histogram> histograms = metricRegistry.getHistograms();
        if (histograms.size() > 0) {
            writeHistograms(histograms, writer);
            writer.newLine();
        }

        SortedMap<String, Meter> meters = metricRegistry.getMeters();
        if (meters.size() > 0) {
            writeMeters(meters, writer);
            writer.newLine();
        }

        SortedMap<String, Timer> timers = metricRegistry.getTimers();
        if (timers.size() > 0) {
            writeTimers(timers, writer);
        }

        writer.flush();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}
 
Example #28
Source File: CommonConnectorMetrics.java    From brooklin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PartitionMetrics(String className, String key) {
  super(className, key);
  _rebalanceRate = DYNAMIC_METRICS_MANAGER.registerMetric(_className, _key, REBALANCE_RATE, Meter.class);
  DYNAMIC_METRICS_MANAGER.registerGauge(_className, _key, STUCK_PARTITIONS, _numStuckPartitions::get);
  DYNAMIC_METRICS_MANAGER.registerGauge(_className, _key, NUM_PARTITIONS, _numPartitions::get);

  _aggregatedRebalanceRate = DYNAMIC_METRICS_MANAGER.registerMetric(_className, AGGREGATE, REBALANCE_RATE, Meter.class);

  AtomicLong aggStuckPartitions = AGGREGATED_NUM_STUCK_PARTITIONS.computeIfAbsent(className, k -> new AtomicLong(0));
  DYNAMIC_METRICS_MANAGER.registerGauge(_className, AGGREGATE, STUCK_PARTITIONS, aggStuckPartitions::get);

  AtomicLong aggNumPartitions = AGGREGATED_NUM_PARTITIONS.computeIfAbsent(className, k -> new AtomicLong(0));
  DYNAMIC_METRICS_MANAGER.registerGauge(_className, AGGREGATE, NUM_PARTITIONS, aggNumPartitions::get);
}
 
Example #29
Source File: Helper.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
public static JsonObject convertMetric(Metric metric, TimeUnit rateUnit, TimeUnit durationUnit) {
  if (metric instanceof Timer) {
    return toJson((Timer) metric, rateUnit, durationUnit);
  } else if (metric instanceof Gauge) {
    return toJson((Gauge) metric);
  } else if (metric instanceof Counter) {
    return toJson((Counter) metric);
  } else if (metric instanceof Histogram) {
    return toJson((Histogram) metric);
  } else if (metric instanceof Meter) {
    return toJson((Meter) metric, rateUnit);
  } else {
    throw new IllegalArgumentException("Unknown metric " + metric);
  }
}
 
Example #30
Source File: KafkaReporter.java    From metrics-kafka with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void report(SortedMap<String, Gauge> gauges,
		SortedMap<String, Counter> counters,
		SortedMap<String, Histogram> histograms,
		SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
	
	final Map<String, Object> result = new HashMap<String, Object>(16);
	
	result.put("hostName", hostName);
	result.put("ip", ip);
	result.put("rateUnit", getRateUnit());
	result.put("durationUnit", getDurationUnit());
	
	result.put("gauges", addPrefix(gauges));
	result.put("counters", addPrefix(counters));
	result.put("histograms", addPrefix(histograms));
	result.put("meters", addPrefix(meters));
	result.put("timers", addPrefix(timers));
	
	result.put("clock", System.currentTimeMillis());
	
	kafkaExecutor.execute(new Runnable() {
		@Override
		public void run() {
			try {
			KeyedMessage<String, String> message = new KeyedMessage<String, String>(
					topic, "" + count++, mapper.writeValueAsString(result));
				producer.send(message);
			} catch (Exception e) {
				logger.error("send metrics to kafka error!", e);
			}
		}
	});
}