Java Code Examples for com.codahale.metrics.Timer#update()

The following examples show how to use com.codahale.metrics.Timer#update() . 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: VideoService.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
private Consumer<PlatformMessage> consumer(MethodListener listener) {
   return (message) -> {
      long startTime = System.nanoTime();
      String type = message.getMessageType();
      try {
         listener.onEvent(message, message.getValue());

         Timer success = MESSAGE_SUCCESS.get(type);
         if (success != null) {
            success.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
         }
      } catch(Exception e) {
         log.warn("Error processing event", e);
         Timer fail = MESSAGE_FAIL.get(type);
         if (fail != null) {
            fail.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
         }
      }
   };
}
 
Example 2
Source File: TestStageContext.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T createMetrics(StageContext context, String metricName, Class<T> metricClass, final Object value) {
  if (metricClass.equals(Meter.class)) {
    Meter m = context.createMeter(metricName);
    m.mark((long)value);
    return (T)m;
  } else if (metricClass.equals(Counter.class)) {
    Counter c = context.createCounter(metricName);
    c.inc((long)value);
    return (T)c;
  } else if (metricClass.equals(Timer.class)) {
    Timer t = context.createTimer(metricName);
    t.update((long)value, TimeUnit.NANOSECONDS);
    return (T)t;
  } else if (metricClass.equals(Histogram.class)) {
    Histogram h = context.createHistogram(metricName);
    h.update((long)value);
    return (T)h;
  } else {
    Gauge<Map<String, Object>> g = context.createGauge(metricName);
    g.getValue().putAll(((Map)value));
    return (T)g;
  }
}
 
Example 3
Source File: MetricCodecTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests encoding of a Metric object.
 */
@Test
public void testMetricEncode() {
    Counter counter = new Counter();
    Meter meter = new Meter();
    Timer timer = new Timer();

    counter.inc();
    meter.mark();
    timer.update(1, TimeUnit.MILLISECONDS);

    ObjectNode counterJson = metricCodec.encode(counter, context);
    assertThat(counterJson.get("counter"), matchesMetric(counter));

    ObjectNode meterJson = metricCodec.encode(meter, context);
    assertThat(meterJson.get("meter"), matchesMetric(meter));

    ObjectNode timerJson = metricCodec.encode(timer, context);
    assertThat(timerJson.get("timer"), matchesMetric(timer));
}
 
Example 4
Source File: TestMetricRuleEvaluator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoftErrorOnWrongCondition() {
  //create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
  Timer t = MetricsConfigurator.createTimer(metrics, "testSoftErrorOnWrongCondition", PIPELINE_NAME, REVISION);
  t.update(1000, TimeUnit.MILLISECONDS);

  MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testSoftErrorOnWrongCondition",
    "testSoftErrorOnWrongCondition", "testSoftErrorOnWrongCondition", MetricType.TIMER,
    //invalid condition
    MetricElement.TIMER_COUNT, "${valu()>2", false, true, System.currentTimeMillis());
  MetricRuleEvaluator metricRuleEvaluator = new MetricRuleEvaluator(metricsRuleDefinition, metrics,
    new AlertManager(PIPELINE_NAME, PIPELINE_TITLE, REVISION, null, metrics, runtimeInfo, new EventListenerManager()),
      new RuleDefinitionsConfigBean(), 0);
  metricRuleEvaluator.checkForAlerts();

  //get alert gauge
  Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
    AlertsUtil.getAlertGaugeName(metricsRuleDefinition.getId()));
  Assert.assertNotNull(gauge);
  Assert.assertNotNull(((Map<String, Object>) gauge.getValue()).get("exceptionMessage"));
}
 
Example 5
Source File: TestMetricRuleEvaluator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimerNoMatch() {
  //create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
  Timer t = MetricsConfigurator.createTimer(metrics, "testTimerNoMatch", PIPELINE_NAME, REVISION);
  t.update(1000, TimeUnit.MILLISECONDS);
  t.update(2000, TimeUnit.MILLISECONDS);
  t.update(3000, TimeUnit.MILLISECONDS);

  MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testTimerNoMatch", "testTimerNoMatch",
    "testTimerNoMatch", MetricType.TIMER,
    MetricElement.TIMER_COUNT, "${value()>4}", false, true, System.currentTimeMillis());
  MetricRuleEvaluator metricRuleEvaluator = new MetricRuleEvaluator(metricsRuleDefinition, metrics,
    new AlertManager(PIPELINE_NAME, PIPELINE_TITLE, REVISION, null, metrics, runtimeInfo, new EventListenerManager()),
       new RuleDefinitionsConfigBean(), 0);
  metricRuleEvaluator.checkForAlerts();

  //get alert gauge
  Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
    AlertsUtil.getAlertGaugeName(metricsRuleDefinition.getId()));
  Assert.assertNull(gauge);
}
 
Example 6
Source File: TestMetricRuleEvaluator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimerMatchDisabled() {
  //create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
  Timer t = MetricsConfigurator.createTimer(metrics, "testTimerMatchDisabled", PIPELINE_NAME, REVISION);
  t.update(1000, TimeUnit.MILLISECONDS);
  t.update(2000, TimeUnit.MILLISECONDS);
  t.update(3000, TimeUnit.MILLISECONDS);

  MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testTimerMatchDisabled",
    "testTimerMatchDisabled", "testTimerMatchDisabled", MetricType.TIMER, MetricElement.TIMER_COUNT,
    "${value()>2}", false, false, System.currentTimeMillis());
  MetricRuleEvaluator metricRuleEvaluator = new MetricRuleEvaluator(metricsRuleDefinition, metrics,
    new AlertManager(PIPELINE_NAME, PIPELINE_TITLE, REVISION, null, metrics, runtimeInfo, new EventListenerManager()),
      new RuleDefinitionsConfigBean(), 0);
  metricRuleEvaluator.checkForAlerts();

  //get alert gauge
  Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
    AlertsUtil.getAlertGaugeName(metricsRuleDefinition.getId()));
  Assert.assertNull(gauge);
}
 
Example 7
Source File: TestMetricRuleEvaluator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimerMatch() {
  //create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
  Timer t = MetricsConfigurator.createTimer(metrics, "testTimerMatch", PIPELINE_NAME, REVISION);
  t.update(1000, TimeUnit.MILLISECONDS);
  t.update(2000, TimeUnit.MILLISECONDS);
  t.update(3000, TimeUnit.MILLISECONDS);

  MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testTimerMatch", "testTimerMatch",
    "testTimerMatch", MetricType.TIMER,
    MetricElement.TIMER_COUNT, "${value()>2}", false, true, System.currentTimeMillis());
  MetricRuleEvaluator metricRuleEvaluator = new MetricRuleEvaluator(metricsRuleDefinition, metrics,
    new AlertManager(PIPELINE_NAME, PIPELINE_TITLE, REVISION, null, metrics, runtimeInfo, new EventListenerManager()),
      new RuleDefinitionsConfigBean(), 0);
  metricRuleEvaluator.checkForAlerts();

  //get alert gauge
  Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
    AlertsUtil.getAlertGaugeName(metricsRuleDefinition.getId()));
  Assert.assertNotNull(gauge);
  Assert.assertEquals((long)3, ((Map<String, Object>) gauge.getValue()).get("currentValue"));
}
 
Example 8
Source File: MegabusRefProducer.java    From emodb with Apache License 2.0 6 votes vote down vote up
private void trackAverageEventDuration(long durationInNs, int numEvents) {
    if (numEvents == 0) {
        return;
    }

    _eventMeter.mark(numEvents);

    long durationPerEvent = (durationInNs + numEvents - 1) / numEvents;  // round up

    _timers.beginUpdates();
    Timer timer = _timers.timer(_timerName, TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS);
    for (int i = 0; i < numEvents; i++) {
        timer.update(durationPerEvent, TimeUnit.NANOSECONDS);
    }
    _timers.endUpdates();
}
 
Example 9
Source File: ResponseMetricCollector.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete(MessageContext context) {
	String name = null;
	Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL);
	if (successful == null) {
		name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS);
		MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark();
	} else {
		if (! successful) {
			name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code()));
			MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark();
		}
		name = getMetricName(context, RESPONSE_TIME);
		Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name);
		timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS);
	}
}
 
Example 10
Source File: SignalFxReporterTest.java    From signalfx-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testResettingTimer() {
    Timer resettingTimer = sfxMetrics.resettingTimer("resettingTimer", "dimName", "dimValue");
    resettingTimer.update(20, TimeUnit.MILLISECONDS);
    resettingTimer.update(30, TimeUnit.MILLISECONDS);
    reporter.report();
    assertEquals(3, dbank.addDataPoints.size());
    assertEquals(2, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.count").getIntValue());
    assertEquals(20000000, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.min").getIntValue());
    assertEquals(30000000, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.max").getIntValue());
    dbank.addDataPoints.clear();
    resettingTimer.update(25, TimeUnit.MILLISECONDS);
    reporter.report();
    assertEquals(3, dbank.addDataPoints.size());
    assertEquals(3, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.count").getIntValue());
    assertEquals(25000000, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.min").getIntValue());
    assertEquals(25000000, dbank.lastValueFor(SOURCE_NAME, "resettingTimer.max").getIntValue());
}
 
Example 11
Source File: Canary.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void trackAverageEventDuration(long durationInNs, int numEvents) {
    if (numEvents == 0) {
        return;
    }

    long durationPerEvent = (durationInNs + numEvents - 1) / numEvents;  // round up

    _timers.beginUpdates();
    Timer timer = _timers.timer(_timerName, TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS);
    for (int i = 0; i < numEvents; i++) {
        timer.update(durationPerEvent, TimeUnit.NANOSECONDS);
    }
    _timers.endUpdates();
}
 
Example 12
Source File: ConnectionProxyFactoryPerformanceTest.java    From flexy-pool with Apache License 2.0 5 votes vote down vote up
private void callConnectionMethods(Timer timer) throws SQLException {
    long startNanos = System.nanoTime();
    try {
        connectionDecorator.getMetaData();
        String javaVersion = System.getProperty("java.version");
        if (javaVersion.contains("1.7") || javaVersion.contains("1.8")) {
            connectionDecorator.setSchema("schema");
            connectionDecorator.abort(null);
        }
    } finally {
        long endNanos = System.nanoTime();
        timer.update((endNanos - startNanos), TimeUnit.NANOSECONDS);
    }
}
 
Example 13
Source File: BlobStoreSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void updateTimer(final String name, final long value) {
  if (metricRegistry != null) {
    Timer timer = timers.computeIfAbsent(name, key ->
        metricRegistry.timer(getClass().getName().replaceAll("\\$.*", "") + '.' + name + ".timer"));
    timer.update(value, TimeUnit.NANOSECONDS);
  }
}
 
Example 14
Source File: CodahaleMetrics.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public void updateTimer(String name, long duration, TimeUnit unit) {
    String key = name;
    try {
        timersLock.lock();
        Timer timer = timers.get(key);
        timer.update(duration, unit);
    } catch (ExecutionException e) {
        throw new IllegalStateException("Error retrieving timer " + name + " from the metric registry ", e);
    } finally {
        timersLock.unlock();
    }
}
 
Example 15
Source File: AsyncTimer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private <V> ListenableFuture<V> time(ListenableFuture<V> operation)
{
   FutureCallback<V> callback = new FutureCallback<V>()
   {
      @Override
      public void onSuccess(V result)
      {
         updateTimer(successTimer);
      }

      @Override
      public void onFailure(Throwable t)
      {
         updateTimer(failureTimer);
      }

      private void updateTimer(Timer timer)
      {
         long duration = clock.getTick() - startTimeNanos;

         timer.update(duration, NANOSECONDS);
      }
   };

   Futures.addCallback(operation, callback, MoreExecutors.directExecutor());

   return operation;
}
 
Example 16
Source File: RecordSampler.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void updateTimer(Record record) {
  long sampledTimeAtDest = Long.parseLong(record.getHeader().getAttribute(SdcRecordConstants.SDC_SAMPLED_TIME));
  long currentTime = System.currentTimeMillis();
  long timeSpentInOrigin = currentTime - sampledTimeAtDest;
  Timer timer = stageContext.getTimer(SdcRecordConstants.EXTERNAL_SYSTEM_LATENCY);
  if (null == timer) {
    timer = stageContext.createTimer(SdcRecordConstants.EXTERNAL_SYSTEM_LATENCY);
  }
  timer.update(timeSpentInOrigin, TimeUnit.MILLISECONDS);
}
 
Example 17
Source File: CodahaleMetrics.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void updateTimer(String name, long duration, TimeUnit unit) {
    String key = name;
    try {
        timersLock.lock();
        Timer timer = timers.get(key);
        timer.update(duration, unit);
    } catch (ExecutionException e) {
        throw new IllegalStateException("Error retrieving timer " + name + " from the metric registry ", e);
    } finally {
        timersLock.unlock();
    }
}
 
Example 18
Source File: InfluxDBReporterTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithoutTags() throws IOException {

  try (
      MetricContext metricContext =
          MetricContext.builder(this.getClass().getCanonicalName() + ".testInfluxDBReporter").build();

      InfluxDBReporter influxDBReporter = InfluxDBReporter.Factory.newBuilder()
          .withInfluxDBPusher(influxDBPusher)
          .withMetricContextName(CONTEXT_NAME)
          .build(new Properties());) {

    ContextAwareGauge<Long> contextAwareGauge =
        metricContext.newContextAwareGauge("com.linkedin.example.gauge", new Gauge<Long>() {
          @Override
          public Long getValue() {
            return 1000l;
          }
        });

    metricContext.register(MetricRegistry.name(METRIC_PREFIX, GAUGE), contextAwareGauge);
    Counter counter = metricContext.counter(MetricRegistry.name(METRIC_PREFIX, COUNTER));
    Meter meter = metricContext.meter(MetricRegistry.name(METRIC_PREFIX, METER));
    Histogram histogram = metricContext.histogram(MetricRegistry.name(METRIC_PREFIX, HISTOGRAM));
    Timer timer = metricContext.timer(MetricRegistry.name(METRIC_PREFIX, TIMER));

    counter.inc(3l);
    meter.mark(1l);
    meter.mark(2l);
    meter.mark(3l);
    histogram.update(1);
    histogram.update(1);
    histogram.update(2);
    timer.update(1, TimeUnit.SECONDS);
    timer.update(2, TimeUnit.SECONDS);
    timer.update(3, TimeUnit.SECONDS);

    influxDBReporter.report(metricContext.getGauges(), metricContext.getCounters(), metricContext.getHistograms(),
        metricContext.getMeters(), metricContext.getTimers(), metricContext.getTagMap());

    //InfluxDB converts all values to float64 internally
    Assert.assertEquals(getMetricValue(COUNTER, Measurements.COUNT), Float.toString(3f));

    Assert.assertEquals(getMetricValue(GAUGE, null), Float.toString(1000l));
    Assert.assertTrue(getMetricTimestamp(GAUGE, null) <= System.currentTimeMillis());

    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_75TH), Float.toString(2f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_98TH), Float.toString(2f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_99TH), Float.toString(2f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_999TH), Float.toString(2f));

    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.COUNT), Float.toString(3f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MIN), Float.toString(1f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MAX), Float.toString(2f));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MEDIAN), Float.toString(1f));
    Assert.assertTrue(Double.valueOf(getMetricValue(HISTOGRAM, Measurements.MEAN)) > 1f);
    Assert.assertTrue(Double.valueOf(getMetricValue(HISTOGRAM, Measurements.STDDEV)) < 0.5f);

    Assert.assertEquals(getMetricValue(METER, Measurements.RATE_1MIN), Float.toString(0f));
    Assert.assertEquals(getMetricValue(METER, Measurements.RATE_5MIN), Float.toString(0f));
    Assert.assertEquals(getMetricValue(METER, Measurements.COUNT), Float.toString(6f));
    Assert.assertTrue(Double.valueOf(getMetricValue(METER, Measurements.MEAN_RATE)) > 0f);

    Assert.assertEquals(getMetricValue(TIMER, Measurements.RATE_1MIN), Float.toString(0f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.RATE_5MIN), Float.toString(0f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_75TH), Float.toString(3000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_98TH), Float.toString(3000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_99TH), Float.toString(3000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_999TH), Float.toString(3000f));

    Assert.assertEquals(getMetricValue(TIMER, Measurements.COUNT), Float.toString(3f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MIN), Float.toString(1000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MAX), Float.toString(3000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MEAN), Float.toString(2000f));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MEDIAN), Float.toString(2000f));
    Assert.assertTrue(Double.valueOf(getMetricValue(TIMER, Measurements.MEAN_RATE)) > 0f);
    Assert.assertTrue(Double.valueOf(getMetricValue(TIMER, Measurements.STDDEV)) > 0f);

  }
}
 
Example 19
Source File: HadoopCounterReporterTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void testReportMetrics() {
  Gauge<Integer> queueSizeGauge = new Gauge<Integer>() {
    @Override
    public Integer getValue() {
      return 1000;
    }
  };

  Counter recordsProcessedCounter = new Counter();
  recordsProcessedCounter.inc(10l);

  Histogram recordSizeDistributionHistogram = new Histogram(new ExponentiallyDecayingReservoir());
  recordSizeDistributionHistogram.update(1);
  recordSizeDistributionHistogram.update(2);
  recordSizeDistributionHistogram.update(3);

  Meter recordProcessRateMeter = new Meter();
  recordProcessRateMeter.mark(1l);
  recordProcessRateMeter.mark(2l);
  recordProcessRateMeter.mark(3l);

  Timer totalDurationTimer = new Timer();
  totalDurationTimer.update(1, TimeUnit.SECONDS);
  totalDurationTimer.update(2, TimeUnit.SECONDS);
  totalDurationTimer.update(3, TimeUnit.SECONDS);

  SortedMap<String, Counter> counters = ImmutableSortedMap.<String, Counter>naturalOrder()
      .put(RECORDS_PROCESSED, recordsProcessedCounter).build();
  SortedMap<String, Gauge> gauges = ImmutableSortedMap.<String, Gauge>naturalOrder()
      .put(QUEUE_SIZE, queueSizeGauge).build();
  SortedMap<String, Histogram> histograms = ImmutableSortedMap.<String, Histogram>naturalOrder()
      .put(RECORD_SIZE_DISTRIBUTION, recordSizeDistributionHistogram).build();
  SortedMap<String, Meter> meters = ImmutableSortedMap.<String, Meter>naturalOrder()
      .put(RECORD_PROCESS_RATE, recordProcessRateMeter).build();
  SortedMap<String, Timer> timers = ImmutableSortedMap.<String, Timer>naturalOrder()
      .put(TOTAL_DURATION, totalDurationTimer).build();

  this.hadoopCounterReporter.report(gauges, counters, histograms, meters, timers);

  Mockito.verify(this.recordsProcessedCount).increment(10l);
  Mockito.verify(this.recordProcessRateCount).increment(6l);
  Mockito.verify(this.recordSizeDistributionCount).increment(3l);
  Mockito.verify(this.totalDurationCount).increment(3l);
  Mockito.verify(this.queueSize).setValue(1000);

  recordsProcessedCounter.inc(5l);
  recordSizeDistributionHistogram.update(4);
  recordProcessRateMeter.mark(4l);
  totalDurationTimer.update(4, TimeUnit.SECONDS);

  this.hadoopCounterReporter.report(gauges, counters, histograms, meters, timers);

  Mockito.verify(this.recordsProcessedCount).increment(5l);
  Mockito.verify(this.recordProcessRateCount).increment(4l);
  Mockito.verify(this.recordSizeDistributionCount).increment(1l);
  Mockito.verify(this.totalDurationCount).increment(1l);
}
 
Example 20
Source File: GraphiteReporterTest.java    From styx with Apache License 2.0 4 votes vote down vote up
private static Timer timer(int update) {
    Timer okTimer = new Timer();
    okTimer.update(update, MILLISECONDS);
    return okTimer;
}