com.codahale.metrics.Counter Java Examples

The following examples show how to use com.codahale.metrics.Counter. 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: HadoopMetrics2ReporterTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void metrics2CycleIsNonDestructive() {
    metrics2Reporter.setDropwizardCounters(Collections.unmodifiableSortedMap(new TreeMap<String, Counter>()));
    metrics2Reporter.setDropwizardGauges(Collections.unmodifiableSortedMap(new TreeMap<String, Gauge>()));
    metrics2Reporter.setDropwizardHistograms(Collections.unmodifiableSortedMap(new TreeMap<String, Histogram>()));
    metrics2Reporter.setDropwizardMeters(Collections.unmodifiableSortedMap(new TreeMap<String, Meter>()));
    metrics2Reporter.setDropwizardTimers(Collections.unmodifiableSortedMap(new TreeMap<String, Timer>()));

    MetricsCollector collector = mock(MetricsCollector.class);
    MetricsRecordBuilder recordBuilder = mock(MetricsRecordBuilder.class);

    Mockito.when(collector.addRecord(recordName)).thenReturn(recordBuilder);

    metrics2Reporter.getMetrics(collector, true);
}
 
Example #2
Source File: TimeLimiterMetrics.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private TimeLimiterMetrics(String prefix, Iterable<TimeLimiter> timeLimiters,
    MetricRegistry metricRegistry) {
    requireNonNull(prefix, PREFIX_NULL);
    requireNonNull(timeLimiters, ITERABLE_NULL);
    requireNonNull(metricRegistry);
    this.metricRegistry = metricRegistry;
    timeLimiters.forEach(timeLimiter -> {
            String name = timeLimiter.getName();
            Counter successes = metricRegistry.counter(name(prefix, name, SUCCESSFUL));
            Counter failures = metricRegistry.counter(name(prefix, name, FAILED));
            Counter timeouts = metricRegistry.counter(name(prefix, name, TIMEOUT));
            timeLimiter.getEventPublisher().onSuccess(event -> successes.inc());
            timeLimiter.getEventPublisher().onError(event -> failures.inc());
            timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc());
        }
    );
}
 
Example #3
Source File: MetricsTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void taskStatuses() {
    Counter runningCounter = Metrics.getRegistry().counter("task_status.task_running");
    Counter lostCounter = Metrics.getRegistry().counter("task_status.task_lost");

    long runningVal = runningCounter.getCount();
    Metrics.record(Protos.TaskStatus.newBuilder()
            .setState(Protos.TaskState.TASK_RUNNING)
            .setTaskId(TestConstants.TASK_ID)
            .build());
    Assert.assertEquals(1, runningCounter.getCount() - runningVal);

    long lostVal = lostCounter.getCount();
    Metrics.record(Protos.TaskStatus.newBuilder()
            .setState(Protos.TaskState.TASK_LOST)
            .setTaskId(TestConstants.TASK_ID)
            .build());
    Assert.assertEquals(1, lostCounter.getCount() - lostVal);
}
 
Example #4
Source File: SemanticMetricRegistry.java    From semantic-metrics with Apache License 2.0 6 votes vote down vote up
private void notifyListenerOfAddedMetric(
    final SemanticMetricRegistryListener listener, final Metric metric, final MetricId name
) {
    if (metric instanceof Gauge) {
        listener.onGaugeAdded(name, (Gauge<?>) metric);
    } else if (metric instanceof Counter) {
        listener.onCounterAdded(name, (Counter) metric);
    } else if (metric instanceof Histogram) {
        listener.onHistogramAdded(name, (Histogram) metric);
    } else if (metric instanceof Meter) {
        listener.onMeterAdded(name, (Meter) metric);
    } else if (metric instanceof Timer) {
        listener.onTimerAdded(name, (Timer) metric);
    } else if (metric instanceof DerivingMeter) {
        listener.onDerivingMeterAdded(name, (DerivingMeter) metric);
    } else {
        throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
    }
}
 
Example #5
Source File: DropWizardMetrics.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@code Metric} collected from {@link Counter}.
 *
 * @param dropwizardName the metric name.
 * @param counter the counter object to collect.
 * @return a {@code Metric}.
 */
private Metric collectCounter(String dropwizardName, Counter counter) {
  String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "counter");
  String metricDescription =
      DropWizardUtils.generateFullMetricDescription(dropwizardName, counter);

  MetricDescriptor metricDescriptor =
      MetricDescriptor.create(
          metricName,
          metricDescription,
          DEFAULT_UNIT,
          Type.GAUGE_INT64,
          Collections.<LabelKey>emptyList());
  TimeSeries timeSeries =
      TimeSeries.createWithOnePoint(
          Collections.<LabelValue>emptyList(),
          Point.create(Value.longValue(counter.getCount()), clock.now()),
          null);
  return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
}
 
Example #6
Source File: MetricsBaseTest.java    From quarks with Apache License 2.0 6 votes vote down vote up
private final void counter(String[] data) throws Exception {
    Topology t = newTopology();
    TStream<String> s = t.strings(data);
    s = Metrics.counter(s);

    waitUntilComplete(t, s, data);

    if (metricRegistry != null) {
        SortedMap<String, Counter> counters = metricRegistry.getCounters();
        assertEquals(1, counters.size());
        Collection<Counter> values = counters.values();
        for (Counter v : values) {
            assertEquals(data.length, v.getCount());
        }
    }
}
 
Example #7
Source File: TCPMetricsImpl.java    From vertx-dropwizard-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void disconnected(Long ctx, SocketAddress remoteAddress) {
  openConnections.dec();
  connections.update(System.nanoTime() - ctx, TimeUnit.NANOSECONDS);

  // On network outage the remoteAddress can be null.
  // Do not report the open-connections when it's null
  if (remoteAddress != null) {
    // Remote address connection metrics
    Counter counter = counter("open-connections", remoteAddress.host());
    counter.dec();
    if (counter.getCount() == 0) {
      remove("open-connections", remoteAddress.host());
    }
  }

  // A little clunky, but it's possible we got here after closed has been called
  if (closed) {
    removeAll();
  }
}
 
Example #8
Source File: MetricsTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private void verifyCreatesConfiguredCounterType(Consumer<Metrics> metricsConsumer) {
    final EnumMap<CounterType, Class<? extends Metric>> counterTypeClasses = new EnumMap<>(CounterType.class);
    counterTypeClasses.put(CounterType.counter, Counter.class);
    counterTypeClasses.put(CounterType.flushingCounter, ResettingCounter.class);
    counterTypeClasses.put(CounterType.meter, Meter.class);

    final SoftAssertions softly = new SoftAssertions();

    for (CounterType counterType : CounterType.values()) {
        // given
        metricRegistry = new MetricRegistry();

        // when
        metricsConsumer.accept(new Metrics(metricRegistry, CounterType.valueOf(counterType.name()),
                accountMetricsVerbosity, bidderCatalog));

        // then
        softly.assertThat(metricRegistry.getMetrics()).hasValueSatisfying(new Condition<>(
                metric -> metric.getClass() == counterTypeClasses.get(counterType),
                null));
    }

    softly.assertAll();
}
 
Example #9
Source File: CloudWatchReporterFactoryTest.java    From dropwizard-metrics-cloudwatch with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyDefaultProviderChainIsUsed() throws Exception {
    System.setProperty("aws.accessKeyId", "fake");
    System.setProperty("aws.secretKey", "fake");
    try {
        CloudWatchReporterFactory factory = new CloudWatchReporterFactory();

        MetricRegistry registry = new MetricRegistry();
        Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));
        counter.inc();
        factory.build(registry).report();
        // expecting a 403
    } finally {
        System.clearProperty("aws.accessKeyId");
        System.clearProperty("aws.secretKey");
    }
}
 
Example #10
Source File: TimeLimiterMetricsPublisher.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public void publishMetrics(TimeLimiter timeLimiter) {

    String name = timeLimiter.getName();
    String successfulName = name(prefix, name, SUCCESSFUL);
    String failedName = name(prefix, name, FAILED);
    String timeoutName = name(prefix, name, TIMEOUT);

    Counter successes = metricRegistry.counter(successfulName);
    Counter failures = metricRegistry.counter(failedName);
    Counter timeouts = metricRegistry.counter(timeoutName);

    timeLimiter.getEventPublisher().onSuccess(event -> successes.inc());
    timeLimiter.getEventPublisher().onError(event -> failures.inc());
    timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc());

    List<String> metricNames = Arrays.asList(successfulName, failedName, timeoutName);
    metricsNameMap.put(name, new HashSet<>(metricNames));
}
 
Example #11
Source File: GlobalMQTTMessageCounterTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_incoming_versioned_connects() {
    embeddedChannel.writeInbound(new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1_1).withClientIdentifier("clientID1").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1).withClientIdentifier("clientID2").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt5Builder().withClientIdentifier("clientID3").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt5Builder().withClientIdentifier("clientID4").build());

    final Counter totalIncoming = getCounter(HiveMQMetrics.INCOMING_CONNECT_COUNT.name());

    final Counter totalIncomingMessages = getCounter(HiveMQMetrics.INCOMING_MESSAGE_COUNT.name());

    assertEquals(4, totalIncoming.getCount());
    assertEquals(4, totalIncomingMessages.getCount());

    assertEquals(0, getCounter(HiveMQMetrics.OUTGOING_MESSAGE_COUNT.name()).getCount());
}
 
Example #12
Source File: TestMetricAggregationProcessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInit() throws StageException {

  MetricRegistry metrics = metricAggregationProcessor.getMetrics();
  SortedMap<String, Timer> timers = metrics.getTimers();

  Assert.assertEquals(5, timers.size()); // 1 each for 4 stages, 1 for pipeline

  SortedMap<String, Counter> counters = metrics.getCounters();
  Assert.assertEquals(24, counters.size()); // 4 each for 4 stages, 5 for pipeline, one each for 3 output lanes

  SortedMap<String, Meter> meters = metrics.getMeters();
  Assert.assertEquals(24, meters.size()); // 4 each for 4 stages, 5 for pipeline, one each for 3 output lanes

  SortedMap<String, Histogram> histograms = metrics.getHistograms();
  Assert.assertEquals(20, histograms.size()); // 4 each for 4 stages, 4 for pipeline
}
 
Example #13
Source File: MonotonicCountedMethodBeanTest.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void countedMethodNotCalledYet() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter hasn't been called yet
    assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
}
 
Example #14
Source File: TaskState.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Update record-level metrics.
 *
 * @param recordsWritten number of records written by the writer
 * @param branchIndex fork branch index
 *
 * @deprecated see {@link org.apache.gobblin.instrumented.writer.InstrumentedDataWriterBase}.
 */
public synchronized void updateRecordMetrics(long recordsWritten, int branchIndex) {
  TaskMetrics metrics = TaskMetrics.get(this);
  // chopping branch index from metric name
  // String forkBranchId = ForkOperatorUtils.getForkId(this.taskId, branchIndex);
  String forkBranchId = TaskMetrics.taskInstanceRemoved(this.taskId);

  Counter taskRecordCounter = metrics.getCounter(MetricGroup.TASK.name(), forkBranchId, RECORDS);
  long inc = recordsWritten - taskRecordCounter.getCount();
  taskRecordCounter.inc(inc);
  metrics.getMeter(MetricGroup.TASK.name(), forkBranchId, RECORDS_PER_SECOND).mark(inc);
  metrics.getCounter(MetricGroup.JOB.name(), this.jobId, RECORDS).inc(inc);
  metrics.getMeter(MetricGroup.JOB.name(), this.jobId, RECORDS_PER_SECOND).mark(inc);
}
 
Example #15
Source File: TestMetricsConfigurator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStageCounter() {
  MetricRegistry metrics = new MetricRegistry();
  MetricsConfigurator.createStageCounter(metrics, "a", "name", "0");
  MetricsConfigurator.createStageCounter(metrics, "a", "name", "0");

  // There should be only one metric object
  Assert.assertEquals(1, metrics.getCounters().size());
  Map.Entry<String, Counter> entry = metrics.getCounters().entrySet().iterator().next();
  Assert.assertEquals("a.counter", entry.getKey());
}
 
Example #16
Source File: AbstractMetrics.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
protected Counter counter(String... names) {
  try {
    return registry.counter(nameOf(names));
  } catch (Exception e) {
    return new Counter();
  }
}
 
Example #17
Source File: CountedConstructorBeanTest.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void countedConstructorCalled() {
    long count = 1L + Math.round(Math.random() * 10);
    for (int i = 0; i < count; i++)
        instance.get();

    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter has been called
    assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(count)));
}
 
Example #18
Source File: CountedMethodBeanTest.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(4)
public void removeCounterFromRegistry() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Remove the counter from metrics registry
    registry.remove(COUNTER_NAME);

    try {
        // Call the counted method and assert an exception is thrown
        bean.countedMethod(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return null;
            }
        });
    } catch (Exception cause) {
        assertThat(cause, is(instanceOf(IllegalStateException.class)));
        assertThat(cause.getMessage(), is(equalTo("No counter with name [" + COUNTER_NAME + "] found in registry [" + registry + "]")));
        // Make sure that the counter hasn't been called
        assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #19
Source File: MetricMetadataTest.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveMissing() {
    MetricRegistry metricRegistry = new MetricRegistry();
    MetricMetadata metadata = new MetricMetadataImpl();
    Counter counter = metricRegistry.counter("counter");
    assertFalse(metadata.removeMetric(counter, metricRegistry));
}
 
Example #20
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, U> void counted(@NotNull BiConsumer<T, U> bc, T arg1, U arg2, @NotNull String counterName, long delta) {
    final Counter counter = getNamedCounter(counterName);
    try {
        bc.accept(arg1, arg2);
    }
    finally {
        processCounter(counter, delta);
    }
}
 
Example #21
Source File: Counters.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Counter} for every value of the enumClass.
 * Use {@link #inc(Enum, long)} to increment the counter associated with a enum value
 *
 * @param metricContext that {@link Counter}s will be registered
 * @param enumClass that define the names of {@link Counter}s. One counter is created per value
 * @param instrumentedClass name that will be prefixed in the metric name
 */
public void initialize(final MetricContext metricContext, final Class<E> enumClass, final Class<?> instrumentedClass) {

  Builder<E, Counter> builder = ImmutableMap.builder();

  for (E e : Arrays.asList(enumClass.getEnumConstants())) {
    builder.put(e, metricContext.counter(MetricRegistry.name(instrumentedClass, e.name())));
  }

  counters = builder.build();
}
 
Example #22
Source File: GcmApnsMetricsInitializationTest.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitialization() throws Exception {
   /* Test each default metric to ensure that it is initialized to 0l */
   CassandraAuditor.DEFAULT_METRICS_COUNTERS.stream()
      .forEach(s -> assertEquals(0L, 
            ((Counter) METRICS.getMetrics().get(String.format("%s.%s",CassandraAuditor.SERVICE_NAME,s))).getCount()));

}
 
Example #23
Source File: GlobalMQTTMessageCounterTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public Counter getCounter(final String meterName) {
    final Set<Map.Entry<String, Counter>> entries = metricRegistry.getCounters(new MetricFilter() {
        @Override
        public boolean matches(final String name, final Metric metric) {
            return name.equals(meterName);
        }
    }).entrySet();
    Preconditions.checkState(entries.size() == 1);
    return entries.iterator().next().getValue();
}
 
Example #24
Source File: MetricUtils.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a single instance of metric into a map or flattened object.
 * @param n metric name
 * @param metric metric instance
 * @param propertyFilter limit what properties of a metric are returned
 * @param skipHistograms discard any {@link Histogram}-s and histogram parts of {@link Timer}-s.
 * @param skipAggregateValues discard internal values of {@link AggregateMetric}-s.
 * @param compact use compact representation for counters and gauges.
 * @param simple use simplified representation for complex metrics - instead of a (name, map)
 *             only the selected (name "." key, value) pairs will be produced.
 * @param consumer consumer that accepts produced objects
 */
public static void convertMetric(String n, Metric metric, PropertyFilter propertyFilter, boolean skipHistograms, boolean skipAggregateValues,
                            boolean compact, boolean simple, String separator, BiConsumer<String, Object> consumer) {
  if (metric instanceof Counter) {
    Counter counter = (Counter) metric;
    convertCounter(n, counter, propertyFilter, compact, consumer);
  } else if (metric instanceof Gauge) {
    @SuppressWarnings({"rawtypes"})
    Gauge gauge = (Gauge) metric;
    try {
      convertGauge(n, gauge, propertyFilter, simple, compact, separator, consumer);
    } catch (InternalError ie) {
      if (n.startsWith("memory.") && ie.getMessage().contains("Memory Pool not found")) {
        log.warn("Error converting gauge '{}', possible JDK bug: SOLR-10362", n, ie);
        consumer.accept(n, null);
      } else {
        throw ie;
      }
    }
  } else if (metric instanceof Meter) {
    Meter meter = (Meter) metric;
    convertMeter(n, meter, propertyFilter, simple, separator, consumer);
  } else if (metric instanceof Timer) {
    Timer timer = (Timer) metric;
    convertTimer(n, timer, propertyFilter, skipHistograms, simple, separator, consumer);
  } else if (metric instanceof Histogram) {
    if (!skipHistograms) {
      Histogram histogram = (Histogram) metric;
      convertHistogram(n, histogram, propertyFilter, simple, separator, consumer);
    }
  } else if (metric instanceof AggregateMetric) {
    convertAggregateMetric(n, (AggregateMetric)metric, propertyFilter, skipAggregateValues, simple, separator, consumer);
  }
}
 
Example #25
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, U, R> R counted(@NotNull BiFunction<T, U, R> bf, T arg1, U arg2, @NotNull String counterName, long delta) {
    final Counter counter = getNamedCounter(counterName);
    try {
        return bf.apply(arg1, arg2);
    }
    finally {
        processCounter(counter, delta);
    }
}
 
Example #26
Source File: PacketStatsUiMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    MetricsService service = get(MetricsService.class);
    Map<String, Counter> counters = service.getCounters(filter);
    Counter pimCounter =  counters.get("packetStatisticsComponent.pimFeature.pimPC");
    long pimCount = pimCounter.getCount();
    ObjectNode pimJson = objectNode();
    pimJson.put("PimCounter", pimCount);
    log.info("Received PIM Request");
    sendMessage(PIM_RESP, pimJson);
}
 
Example #27
Source File: MetricTypeFilterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void matchesTest() {
  Counter counter = mock(Counter.class);
  Gauge gauge = mock(Gauge.class);
  Histogram histogram = mock(Histogram.class);
  Meter meter = mock(Meter.class);
  Timer timer = mock(Timer.class);

  MetricTypeFilter noMetricTypeFilter = new MetricTypeFilter(null);
  Assert.assertTrue(noMetricTypeFilter.matches("", counter));
  Assert.assertTrue(noMetricTypeFilter.matches("", gauge));
  Assert.assertTrue(noMetricTypeFilter.matches("", histogram));
  Assert.assertTrue(noMetricTypeFilter.matches("", meter));
  Assert.assertTrue(noMetricTypeFilter.matches("", timer));

  MetricTypeFilter counterMetricTypeFilter = new MetricTypeFilter("COUNTER");
  Assert.assertTrue(counterMetricTypeFilter.matches("", counter));
  Assert.assertFalse(counterMetricTypeFilter.matches("", gauge));
  Assert.assertFalse(counterMetricTypeFilter.matches("", histogram));
  Assert.assertFalse(counterMetricTypeFilter.matches("", meter));
  Assert.assertFalse(counterMetricTypeFilter.matches("", timer));

  MetricTypeFilter allMetricTypeFilter = new MetricTypeFilter("COUNTER,GAUGE,HISTOGRAM,METER,TIMER");
  Assert.assertTrue(allMetricTypeFilter.matches("", counter));
  Assert.assertTrue(allMetricTypeFilter.matches("", gauge));
  Assert.assertTrue(allMetricTypeFilter.matches("", histogram));
  Assert.assertTrue(allMetricTypeFilter.matches("", meter));
  Assert.assertTrue(allMetricTypeFilter.matches("", timer));
}
 
Example #28
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public void report(
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

    logger.info("Starting metrics publishing to AWS CloudWatch.");

    LinkedList<PutMetricDataRequest> requests = new LinkedList<>();

    addMetricData(gauges, counters, histograms, meters, timers, requests, new Date());

    if (requests.isEmpty()) {
        logger.debug("No metric data to send to AWS.");
        return;
    }

    for (PutMetricDataRequest request : requests) {
        try {
            for (MetricDatum datum : request.getMetricData()) {
                logger.debug("Sending metric " + datum);
            }
            cloudWatch.putMetricData(request);
        } catch (Exception e) {
            logger.error("Failed to log metrics to CloudWatch discarding metrics for this attempt...",e);
            return;
        }
    }
    logger.info("Finished metrics publishing to AWS CloudWatch.");
}
 
Example #29
Source File: AsmCounter.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
protected void updateSnapshot(int window) {
    Counter counter = counterMap.get(window);
    if (counter != null) {
        AsmSnapshot snapshot = new AsmCounterSnapshot().setValue(counter.getCount())
                .setTs(System.currentTimeMillis()).setMetricId(metricId);
        snapshots.put(window, snapshot);
    }
}
 
Example #30
Source File: PacketStatsUiMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    MetricsService service = get(MetricsService.class);
    Map<String, Counter> counters = service.getCounters(filter);
    Counter vlanCounter = counters.get("packetStatisticsComponent.vlanFeature.vlanPC");
    long vlanCount = vlanCounter.getCount();
    ObjectNode vlanJson = objectNode();
    vlanJson.put("VlanCounter", vlanCount);
    log.info("Received VLAN Request");
    sendMessage(VLAN_RESP, vlanJson);
}