Java Code Examples for com.codahale.metrics.Gauge

The following examples show how to use com.codahale.metrics.Gauge. These examples are extracted from open source projects. 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 Project: hadoop   Source File: ResourceSchedulerWrapper.java    License: Apache License 2.0 6 votes vote down vote up
private void registerContainerAppNumMetrics() {
  metrics.register("variable.running.application",
    new Gauge<Integer>() {
      @Override
      public Integer getValue() {
        if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
          return 0;
        } else {
          return scheduler.getRootQueueMetrics().getAppsRunning();
        }
      }
    }
  );
  metrics.register("variable.running.container",
    new Gauge<Integer>() {
      @Override
      public Integer getValue() {
        if(scheduler == null || scheduler.getRootQueueMetrics() == null) {
          return 0;
        } else {
          return scheduler.getRootQueueMetrics().getAllocatedContainers();
        }
      }
    }
  );
}
 
Example 2
@SuppressWarnings("unchecked")
private static <T> T getMetricValue(Map<String, Metric> metricMap, String name, Function<Object, T> valueExtractor) {
    Metric metric = metricMap.get(name);
    T value = null;
    if (metric instanceof Gauge) {
        Gauge gauge = (Gauge) metric;
        value = (T) gauge.getValue();
    }
    if (metric instanceof Counter) {
        Counter counter = (Counter) metric;
        value = (T) (Long) counter.getCount();
    }
    if (value != null && valueExtractor != null) {
        value = valueExtractor.apply(value);
    }
    return value;
}
 
Example 3
Source Project: radar   Source File: ClientAppRegisterInstanceController.java    License: Apache License 2.0 6 votes vote down vote up
private void initMetric() {
	MetricSingleton.getMetricRegistry().register(MetricRegistry.name("data.registerInstanceCount"),
			new Gauge<Long>() {
				@Override
				public Long getValue() {
					return registCounter.get();
				}
			});
	MetricSingleton.getMetricRegistry().register(MetricRegistry.name("data.registerInstanceTime"),
			new Gauge<Long>() {
				@Override
				public Long getValue() {
					return registTime;
				}
			});
}
 
Example 4
@Test
public void reportMetersCountersGaugesWithZeroValuesOnlyWhenConfigured() throws Exception {
    metricRegistry.register(ARBITRARY_GAUGE_NAME, (Gauge<Long>) () -> 0L);
    metricRegistry.meter(ARBITRARY_METER_NAME).mark(0);
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(0);
    metricRegistry.timer(ARBITRARY_TIMER_NAME).update(-1L, TimeUnit.NANOSECONDS);

    buildReportWithSleep(reporterBuilder
            .withArithmeticMean()
            .withOneMinuteMeanRate()
            .withFiveMinuteMeanRate()
            .withFifteenMinuteMeanRate()
            .withZeroValuesSubmission()
            .withMeanRate());

    verify(mockAmazonCloudWatchAsyncClient, times(1)).putMetricData(metricDataRequestCaptor.capture());

    final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue();
    final List<MetricDatum> metricData = putMetricDataRequest.metricData();
    for (final MetricDatum metricDatum : metricData) {
        assertThat(metricDatum.value()).isEqualTo(0.0);
    }
}
 
Example 5
Source Project: datacollector   Source File: TestMetricRuleEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCounterDisabled() {
  //create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
  Counter c = MetricsConfigurator.createCounter(metrics, "testCounterDisabled", PIPELINE_NAME, REVISION);
  c.inc(100);

  MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testCounterDisabled",
    "testCounterDisabled", "testCounterDisabled", MetricType.COUNTER,
    MetricElement.COUNTER_COUNT, "${value()>98}", 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 6
Source Project: incubator-ratis   Source File: RaftBasicTests.java    License: Apache License 2.0 6 votes vote down vote up
private static Gauge getStatemachineGaugeWithName(RaftServerImpl server,
    String gaugeName) {

  MetricRegistryInfo info = new MetricRegistryInfo(server.getMemberId().toString(),
      RATIS_APPLICATION_NAME_METRICS,
      RATIS_STATEMACHINE_METRICS, RATIS_STATEMACHINE_METRICS_DESC);

  Optional<RatisMetricRegistry> metricRegistry = MetricRegistries.global().get(info);
  Assert.assertTrue(metricRegistry.isPresent());
  RatisMetricRegistry ratisStateMachineMetricRegistry = metricRegistry.get();

  SortedMap<String, Gauge> gaugeMap =
      ratisStateMachineMetricRegistry.getGauges((s, metric) ->
          s.contains(gaugeName));

  return gaugeMap.get(gaugeMap.firstKey());
}
 
Example 7
Source Project: cassandra-reaper   Source File: Heart.java    License: Apache License 2.0 6 votes vote down vote up
private void registerGauges() throws IllegalArgumentException {
  if (!GAUGES_REGISTERED.getAndSet(true)) {

    context.metricRegistry.register(
        MetricRegistry.name(Heart.class, "runningThreadCount"),
        (Gauge<Integer>) () -> forkJoinPool.getRunningThreadCount());

    context.metricRegistry.register(
        MetricRegistry.name(Heart.class, "activeThreadCount"),
        (Gauge<Integer>) () -> forkJoinPool.getActiveThreadCount());

    context.metricRegistry.register(
        MetricRegistry.name(Heart.class, "queuedTaskCount"),
        (Gauge<Long>) () -> forkJoinPool.getQueuedTaskCount());

    context.metricRegistry.register(
        MetricRegistry.name(Heart.class, "queuedSubmissionCount"),
        (Gauge<Integer>) () -> forkJoinPool.getQueuedSubmissionCount());
  }
}
 
Example 8
Source Project: incubator-ratis   Source File: RaftBasicTests.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) {
  List<RaftServerImpl> followers = cluster.getFollowers();
  RaftServerImpl leader = cluster.getLeader();

  Gauge leaderCommitGauge = RaftServerMetrics
      .getPeerCommitIndexGauge(leader, leader);

  for (RaftServerImpl follower : followers) {
    Gauge followerCommitGauge = RaftServerMetrics
        .getPeerCommitIndexGauge(leader, follower);
    Assert.assertTrue((Long)leaderCommitGauge.getValue() >=
        (Long)followerCommitGauge.getValue());
    Gauge followerMetric = RaftServerMetrics
        .getPeerCommitIndexGauge(follower, follower);
    System.out.println(followerCommitGauge.getValue());
    System.out.println(followerMetric.getValue());
    Assert.assertTrue((Long)followerCommitGauge.getValue()  <= (Long)followerMetric.getValue());
  }
}
 
Example 9
@Inject
public PlatformDriverExecutorRegistry(
      DriverConfig config,
      DriverRegistry registry, 
      DeviceDAO deviceDao, 
      Scheduler scheduler, 
      PlacePopulationCacheManager populationCacheMgr
) {
   this.driverQueueBacklog = config.getDriverBacklogSize();
   this.tombstonedDriverTimeoutMs = config.getDriverTombstoneTimeout(TimeUnit.MILLISECONDS);
   this.registry = registry;
   this.deviceDao = deviceDao;
   this.scheduler = scheduler;
   this.populationCacheMgr = populationCacheMgr;
   IrisMetricSet drivers = IrisMetrics.metrics("drivers");
   drivers.monitor("cache.executor", executorCache);
   drivers.monitor("cache.protocol", protocolToDriverCache);
   drivers.gauge("backlog", (Gauge<Map<String, Object>>) () -> queueBacklog());
}
 
Example 10
@Test
public void testGaugeMetric() {
    SortedMap<String, Gauge> gauges = new TreeMap<>();
    Gauge<Number> gauge = new Gauge<Number>() {

        @Override
        public Number getValue() {
            return new Double(METRIC_VALUE);
        }

    };
    gauges.put(GAUGE_METRIC, gauge);
    List<Metric> metrics = new GaugeConverter().convert(gauges, currentTimeMillis);
    ConverterTestUtil util =
        new ConverterTestUtil(metrics, GAUGE_METRIC, MetricType.GAUGE.getMetricTypeName(), currentTimeMillis);
    util.checkMetric(SUFFIX_VALUE, METRIC_VALUE);
    assertEquals(1, metrics.size());
}
 
Example 11
@Test
public void testUpdateMetricsProcessor() throws InitializationException, IOException {
    MetricsService ms = new MetricsService();
    Map<String, Double> processorMetrics = ms.getProcessorMetrics(procStatus);
    Map<String, String> tagsMap = ImmutableMap.of("env", "test");
    DataDogReportingTask dataDogReportingTask = new TestableDataDogReportingTask();
    dataDogReportingTask.initialize(initContext);
    dataDogReportingTask.setup(configurationContext);
    dataDogReportingTask.updateMetrics(processorMetrics, Optional.of("sampleProcessor"), tagsMap);

    verify(metricRegistry).register(eq("nifi.sampleProcessor.FlowFilesReceivedLast5Minutes"), Mockito.<Gauge>any());
    verify(metricRegistry).register(eq("nifi.sampleProcessor.ActiveThreads"), Mockito.<Gauge>any());
    verify(metricRegistry).register(eq("nifi.sampleProcessor.BytesWrittenLast5Minutes"), Mockito.<Gauge>any());
    verify(metricRegistry).register(eq("nifi.sampleProcessor.BytesReadLast5Minutes"), Mockito.<Gauge>any());
    verify(metricRegistry).register(eq("nifi.sampleProcessor.FlowFilesSentLast5Minutes"), Mockito.<Gauge>any());
}
 
Example 12
Source Project: lucene-solr   Source File: SystemInfoHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testMagickGetter() throws Exception {

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    // make one directly
    SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
    info.add( "name", os.getName() );
    info.add( "version", os.getVersion() );
    info.add( "arch", os.getArch() );

    // make another using MetricUtils.addMXBeanMetrics()
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    MetricUtils.addMXBeanMetrics( os, OperatingSystemMXBean.class, null, (k, v) -> {
      info2.add(k, ((Gauge)v).getValue());
    } );

    // make sure they got the same thing
    for (String p : Arrays.asList("name", "version", "arch")) {
      assertEquals(info.get(p), info2.get(p));
    }
  }
 
Example 13
Source Project: Bats   Source File: RootAllocator.java    License: Apache License 2.0 5 votes vote down vote up
public RootAllocator(final long limit) {
  super(null, "ROOT", 0, limit);
  DrillMetrics.register("drill.allocator.root.used", new Gauge<Long>() {
    @Override
    public Long getValue() {
      return getAllocatedMemory();
    }
  });
  DrillMetrics.register("drill.allocator.root.peak", new Gauge<Long>() {
    @Override
    public Long getValue() {
      return getPeakMemoryAllocation();
    }
  });
}
 
Example 14
public DynamoDbDelegate(final String endpoint, final String region, final AWSCredentialsProvider provider,
    final ClientConfiguration clientConfig, final Configuration titanConfig,
    final Map<String, RateLimiter> readRateLimit, final Map<String, RateLimiter> writeRateLimit,
    final long maxRetries, final long retryMillis, final String prefix, final String metricsPrefix,
    final RateLimiter controlPlaneRateLimiter) {
    if (prefix == null) {
        throw new IllegalArgumentException("prefix must be set");
    }
    if (metricsPrefix == null || metricsPrefix.isEmpty()) {
        throw new IllegalArgumentException("metrics-prefix may not be null or empty");
    }
    this.metricsPrefix = metricsPrefix;
    executorGaugeName = String.format("%s.%s_executor-queue-size", this.metricsPrefix, prefix);
    clientThreadPool = getPoolFromNs(titanConfig);
    if (!MetricManager.INSTANCE.getRegistry().getNames().contains(executorGaugeName)) {
        MetricManager.INSTANCE.getRegistry().register(executorGaugeName, (Gauge<Integer>) () -> clientThreadPool.getQueue().size());
    }

    client = AmazonDynamoDBClientBuilder.standard()
            .withCredentials(provider)
            .withClientConfiguration(clientConfig)
            .withEndpointConfiguration(getEndpointConfiguration(Optional.ofNullable(endpoint), region))
        .build();
    this.readRateLimit = readRateLimit;
    this.writeRateLimit = writeRateLimit;
    this.controlPlaneRateLimiter = controlPlaneRateLimiter;
    this.maxConcurrentUsers = titanConfig.get(Constants.DYNAMODB_CLIENT_EXECUTOR_MAX_CONCURRENT_OPERATIONS);
    this.maxRetries = maxRetries;
    this.retryMillis = retryMillis;
    if (maxConcurrentUsers < 1) {
        throw new IllegalArgumentException("need at least one user otherwise wont make progress on scan");
    }
    this.listTablesApiName = String.format("%s_ListTables", prefix);
}
 
Example 15
Source Project: eagle   Source File: MetricEvent.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( {"rawtypes", "unchecked"})
public Builder from(Gauge gauge) {
    Object value = gauge.getValue();
    if (value instanceof Map) {
        Map<? extends String, ?> map = (Map<? extends String, ?>) value;
        this.instance.putAll(map);
    } else {
        this.instance.put("value", value);
    }
    return this;
}
 
Example 16
Source Project: sofa-jraft   Source File: ThreadPoolMetricSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return thread pool metrics
 * @return thread pool metrics map
 */
@Override
public Map<String, Metric> getMetrics() {
    final Map<String, Metric> gauges = new HashMap<>();
    gauges.put("pool-size", (Gauge<Integer>) executor::getPoolSize);
    gauges.put("queued", (Gauge<Integer>) executor.getQueue()::size);
    gauges.put("active", (Gauge<Integer>) executor::getActiveCount);
    gauges.put("completed", (Gauge<Long>) executor::getCompletedTaskCount);
    return gauges;
}
 
Example 17
Source Project: sofa-jraft   Source File: Replicator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Metric> getMetrics() {
    final Map<String, Metric> gauges = new HashMap<>();
    gauges.put("log-lags",
        (Gauge<Long>) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1));
    gauges.put("next-index", (Gauge<Long>) () -> this.r.nextIndex);
    gauges.put("heartbeat-times", (Gauge<Long>) () -> this.r.heartbeatCounter);
    gauges.put("install-snapshot-times", (Gauge<Long>) () -> this.r.installSnapshotCounter);
    gauges.put("append-entries-times", (Gauge<Long>) () -> this.r.appendEntriesCounter);
    return gauges;
}
 
Example 18
Source Project: pmq   Source File: MqLockServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void initMetric() {
    MetricSingleton.getMetricRegistry().register(key + ".Count", new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return isMaster ? 1 : 0;
        }
    });
}
 
Example 19
@Test
public void registerNamedMetric_registers_metric_using_sfx_mechanisms() {
    // given
    String gaugeName = UUID.randomUUID().toString();

    // when
    Gauge<String> result = sfxImpl.registerNamedMetric(gaugeName, gaugeMock);

    // then
    verifyMetricRegistration(gaugeTaggerMock, gaugeName, gaugeMock, result);
}
 
Example 20
Source Project: cf-java-logging-support   Source File: GaugeConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<Metric> convertMetricEntry(Entry<String, Gauge> metricEntry, long timestamp) {
    List<Metric> result = new ArrayList<>();
    Object gaugeValue = metricEntry.getValue().getValue();
    if (gaugeValue instanceof Number) {
        Number number = (Number) gaugeValue;
        result.add(buildCustomMetric(metricEntry.getKey() + ".value", number.doubleValue(), MetricType.GAUGE,
                                     timestamp));
    } else {
        throw new IllegalArgumentException(String.format("The type {%s} for Gauge {%s} is invalid. The supported type is {%s}", gaugeValue.getClass().getName(), metricEntry.getKey(), Number.class.getName()));
    }
    return result;
}
 
Example 21
Source Project: rolling-metrics   Source File: TopMetricSet.java    License: Apache License 2.0 5 votes vote down vote up
private Gauge<BigDecimal> createLatencyGauge(int i, Top top, TimeUnit latencyUnit, int digitsAfterDecimalPoint) {
    return () -> {
        List<Position> positions = top.getPositionsInDescendingOrder();
        if (positions.size() <= i) {
            return zero;
        }
        double latencyNanos = positions.get(i).getLatencyInNanoseconds();
        long scale = latencyUnit.toNanos(1);
        double result = latencyNanos/scale;

        return new BigDecimal(result).setScale(digitsAfterDecimalPoint, RoundingMode.CEILING);
    };
}
 
Example 22
Source Project: styx   Source File: NettyAllocatorMetricSetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void gaugeReportsHeapMemoryUsageValue() throws Exception {
    when(metricUnderTest.usedHeapMemory()).thenReturn(1L);
    NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest);

    Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedHeapMemory");
    assertThat(metric.getValue(), is(1L));
}
 
Example 23
Source Project: rubix   Source File: CoordinatorBookKeeper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Register desired metrics.
 */
private void registerMetrics()
{
  metrics.register(BookKeeperMetrics.HealthMetric.LIVE_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
  {
    @Override
    public Long getValue()
    {
      // Clean up cache to ensure accurate size is reported.
      liveWorkerCache.cleanUp();
      log.debug(String.format("Reporting %d live workers", liveWorkerCache.size()));
      return liveWorkerCache.size();
    }
  });

  if (isValidationEnabled) {
    metrics.register(BookKeeperMetrics.HealthMetric.CACHING_VALIDATED_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
    {
      @Override
      public Long getValue()
      {
        // Clean up cache to ensure accurate size is reported.
        cachingValidatedWorkerCache.cleanUp();
        log.debug(String.format("Caching validation passed for %d workers", cachingValidatedWorkerCache.size()));
        return cachingValidatedWorkerCache.size();
      }
    });
    metrics.register(BookKeeperMetrics.HealthMetric.FILE_VALIDATED_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
    {
      @Override
      public Long getValue()
      {
        // Clean up cache to ensure accurate size is reported.
        fileValidatedWorkerCache.cleanUp();
        log.debug(String.format("File validation passed for %d workers", fileValidatedWorkerCache.size()));
        return fileValidatedWorkerCache.size();
      }
    });
  }
}
 
Example 24
Source Project: watcher   Source File: GaugeSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
	Gauge gauge = (Gauge) object;
	Object value = gauge.getValue();
	SerializeWriter writer = serializer.getWriter();
	if (value == null)
		writer.write("0");
	else
		writer.write(value.toString());
}
 
Example 25
Source Project: incubator-retired-gossip   Source File: GossipCore.java    License: Apache License 2.0 5 votes vote down vote up
public GossipCore(GossipManager manager, MetricRegistry metrics){
  this.gossipManager = manager;
  requests = new ConcurrentHashMap<>();
  perNodeData = new ConcurrentHashMap<>();
  sharedData = new ConcurrentHashMap<>();
  eventManager = new DataEventManager(metrics);
  metrics.register(PER_NODE_DATA_SIZE, (Gauge<Integer>)() -> perNodeData.size());
  metrics.register(SHARED_DATA_SIZE, (Gauge<Integer>)() ->  sharedData.size());
  metrics.register(REQUEST_SIZE, (Gauge<Integer>)() ->  requests.size());
  messageSerdeException = metrics.meter(MESSAGE_SERDE_EXCEPTION);
  transmissionException = metrics.meter(MESSAGE_TRANSMISSION_EXCEPTION);
  transmissionSuccess = metrics.meter(MESSAGE_TRANSMISSION_SUCCESS);
}
 
Example 26
Source Project: styx   Source File: DashboardData.java    License: Apache License 2.0 5 votes vote down vote up
private ConnectionsPool() {
    String prefix = format("origins.%s.%s.connectionspool", origin.applicationId(), origin.id());

    SortedMap<String, Gauge> gauges = metrics.getGauges();

    availableGauge = gauges.get(prefix + ".available-connections");
    busyGauge = gauges.get(prefix + ".busy-connections");
    pendingGauge = gauges.get(prefix + ".pending-connections");
}
 
Example 27
Source Project: datacollector   Source File: TestDataObserverRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleObserverRequestAlert() {
  RulesConfigurationChangeRequest rulesConfigurationChangeRequest = createRulesConfigurationChangeRequest(true, false);
  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"));
}
 
Example 28
Source Project: big-c   Source File: ResourceSchedulerWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private void registerJvmMetrics() {
  // add JVM gauges
  metrics.register("variable.jvm.free.memory",
    new Gauge<Long>() {
      @Override
      public Long getValue() {
        return Runtime.getRuntime().freeMemory();
      }
    }
  );
  metrics.register("variable.jvm.max.memory",
    new Gauge<Long>() {
      @Override
      public Long getValue() {
        return Runtime.getRuntime().maxMemory();
      }
    }
  );
  metrics.register("variable.jvm.total.memory",
    new Gauge<Long>() {
      @Override
      public Long getValue() {
        return Runtime.getRuntime().totalMemory();
      }
    }
  );
}
 
Example 29
@Test
public void reportsIncludedMeters() throws Exception {

    InfluxDbReporter filteredReporter = InfluxDbReporter
        .forRegistry(registry)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .filter(MetricFilter.ALL)
        .groupGauges(true)
        .includeMeterFields(Sets.newSet("m1_rate"))
        .build(influxDb);


    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);

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

    final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class);
    verify(influxDb, atLeastOnce()).appendPoints(influxDbPointCaptor.capture());
    InfluxDbPoint point = influxDbPointCaptor.getValue();

    assertThat(point.getMeasurement()).isEqualTo("filteredMeter");
    assertThat(point.getFields()).isNotEmpty();
    assertThat(point.getFields()).hasSize(1);
    assertThat(point.getFields()).contains(entry("m1_rate", 2.0));
    assertThat(point.getTags()).containsEntry("metricName", "filteredMeter");
}
 
Example 30
Source Project: hugegraph   Source File: ServerReporter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void report(SortedMap<String, Gauge> gauges,
                   SortedMap<String, Counter> counters,
                   SortedMap<String, Histogram> histograms,
                   SortedMap<String, Meter> meters,
                   SortedMap<String, Timer> timers) {
    this.gauges = (SortedMap) gauges;
    this.counters = counters;
    this.histograms = histograms;
    this.meters = meters;
    this.timers = timers;
}