Java Code Examples for com.codahale.metrics.Counter#inc()

The following examples show how to use com.codahale.metrics.Counter#inc() . 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: TestMetricRuleEvaluator.java    From datacollector with 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 2
Source File: KafkaReporterTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test
public void kafkaReporterContextTest() throws IOException {
  Tag<?> tag1 = new Tag<>("tag1", "value1");
  MetricContext context = MetricContext.builder("context").addTag(tag1).build();
  Counter counter = context.counter("com.linkedin.example.counter");

  MockKafkaPusher pusher = new MockKafkaPusher();
  KafkaReporter kafkaReporter = getBuilderFromContext(pusher).build("localhost:0000", "topic", new Properties());

  counter.inc();

  kafkaReporter.report(context);

  try {
    Thread.sleep(1000);
  } catch (InterruptedException ex) {
    Thread.currentThread().interrupt();
  }

  MetricReport metricReport = nextReport(pusher.messageIterator());

  Assert.assertEquals(3, metricReport.getTags().size());
  Assert.assertTrue(metricReport.getTags().containsKey(tag1.getKey()));
  Assert.assertEquals(metricReport.getTags().get(tag1.getKey()), tag1.getValue().toString());

}
 
Example 3
Source File: SolrMetricTestUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static Map<String, Counter> getRandomMetricsWithReplacements(Random random, Map<String, Counter> existing) {
  HashMap<String, Counter> metrics = new HashMap<>();
  ArrayList<String> existingKeys = new ArrayList<>(existing.keySet());

  int numMetrics = TestUtil.nextInt(random, 1, MAX_ITERATIONS);
  for (int i = 0; i < numMetrics; ++i) {
    boolean shouldReplaceMetric = !existing.isEmpty() && random.nextBoolean();
    String name = shouldReplaceMetric
        ? existingKeys.get(TestUtil.nextInt(random, 0, existingKeys.size() - 1))
        : TestUtil.randomSimpleString(random, 5, 10) + SUFFIX; // must be simple string for JMX publishing

    Counter counter = new Counter();
    counter.inc(random.nextLong());
    metrics.put(name, counter);
  }

  return metrics;
}
 
Example 4
Source File: MetricTypesExample.java    From semantic-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * A counter is just a gauge for an AtomicLong instance. You can increment or decrement its
 * value. We want a more efficient way of measuring the pending job in a queue
 */
private static void reportCounter() {
    // Create or fetch (if it is already created) the metric.
    final Counter counter = registry.counter(APP_PREFIX.tagged("what", "job-count"));

    // Somewhere in your code where you are adding new jobs to the queue you increment the
    // counter as well
    counter.inc();

    // Oh look! Another job!
    counter.inc();

    // Somewhere in your code the job is going to be removed from the queue you decrement the
    // counter
    counter.dec();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, the current value of the counter will be read
    // and
    // a datapoint will be created and reported.
}
 
Example 5
Source File: MetricsManager.java    From ache with Apache License 2.0 6 votes vote down vote up
/**
 * Loads metrics from the file at the directory path
 * 
 * @param metricsRegistry
 * @param directoryPath
 * @return
 * @throws IOException
 */
private MetricRegistry loadMetrics(MetricRegistry metricsRegistry, String directoryPath) {
    File metricsFile = new File(directoryPath + "/metrics/metrics_counters.data");
    if (metricsFile.exists()) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(metricsFile));
            String line = null;
            while ((line = reader.readLine()) != null) {
                String[] input = line.split(":");
                Counter counter = metricsRegistry.counter(input[0]);
                counter.inc(Integer.parseInt(input[1]));
            }
            reader.close();
        } catch (Exception e) {
            logger.error("Unable to deserialize counters : " + e.getMessage());
        }
    }
    return metricsRegistry;
}
 
Example 6
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 7
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 8
Source File: NonBlockingRouterMetrics.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Update appropriate metrics on a getBlob (Data or All) operation related error.
 * @param e the {@link Exception} associated with the error.
 * @param options the {@link GetBlobOptionsInternal} associated with the request.
 * @param encrypted {@code true} if blob is encrypted, {@code false} otherwise
 */
private void onGetBlobDataError(Exception e, GetBlobOptionsInternal options, boolean encrypted) {
  onError(e);
  Counter blobErrorCount = encrypted ? getEncryptedBlobErrorCount : getBlobErrorCount;
  Counter blobWithRangeErrorCount = encrypted ? getEncryptedBlobWithRangeErrorCount : getBlobWithRangeErrorCount;
  Counter blobWithSegmentErrorCount =
      encrypted ? getEncryptedBlobWithSegmentErrorCount : getBlobWithSegmentErrorCount;
  Meter operationErrorRateMeter = encrypted ? encryptedOperationErrorRate : operationErrorRate;
  if (RouterUtils.isSystemHealthError(e)) {
    blobErrorCount.inc();
    if (options != null) {
      if (options.getBlobOptions.getRange() != null) {
        blobWithRangeErrorCount.inc();
      }
      if (options.getBlobOptions.hasBlobSegmentIdx()) {
        blobWithSegmentErrorCount.inc();
      }
    }
    operationErrorRateMeter.mark();
  }
}
 
Example 9
Source File: MetricsHelper.java    From datacollector with Apache License 2.0 6 votes vote down vote up
static Counter createAndInitCounter(
    MetricRegistryJson metricRegistryJson,
    MetricRegistry metrics,
    String counterName,
    String pipelineName,
    String revision
) {
  Counter counter = MetricsConfigurator.createCounter(metrics, counterName, pipelineName, revision);
  if (metricRegistryJson != null) {
    Map<String, CounterJson> counters = metricRegistryJson.getCounters();
    if (null != counters && counters.containsKey(counterName + MetricsConfigurator.COUNTER_SUFFIX)) {
      CounterJson counterJson = counters.get(counterName + MetricsConfigurator.COUNTER_SUFFIX);
      if (counterJson != null) {
        counter.inc(counterJson.getCount());
      }
    }
  }
  return counter;
}
 
Example 10
Source File: KafkaReporterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void kafkaReporterTagsTest() throws IOException {
  MetricContext metricContext =
      MetricContext.builder(this.getClass().getCanonicalName() + ".kafkaReporterTagsTest").build();
  Counter counter = metricContext.counter("com.linkedin.example.counter");

  Tag<?> tag1 = new Tag<>("tag1", "value1");
  Tag<?> tag2 = new Tag<>("tag2", 2);

  MockKafkaPusher pusher = new MockKafkaPusher();
  KafkaReporter kafkaReporter =
      getBuilder(pusher).withTags(Lists.newArrayList(tag1, tag2)).build("localhost:0000", "topic", new Properties());

  counter.inc();

  kafkaReporter.report(metricContext);

  try {
    Thread.sleep(1000);
  } catch (InterruptedException ex) {
    Thread.currentThread().interrupt();
  }

  MetricReport metricReport = nextReport(pusher.messageIterator());

  Assert.assertEquals(4, metricReport.getTags().size());
  Assert.assertTrue(metricReport.getTags().containsKey(tag1.getKey()));
  Assert.assertEquals(metricReport.getTags().get(tag1.getKey()), tag1.getValue().toString());
  Assert.assertTrue(metricReport.getTags().containsKey(tag2.getKey()));
  Assert.assertEquals(metricReport.getTags().get(tag2.getKey()), tag2.getValue().toString());
}
 
Example 11
Source File: LocalRangeScanUploader.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void closeAndTransfer(ScanDestinationWriter writer,
                              int partCount, Counter shardCounter, boolean isFinalPart)
        throws IOException {
    if (isFinalPart) {
        shardCounter.inc();
    }
    writer.closeAndTransferAsync(isFinalPart ? Optional.of(partCount) : Optional.<Integer>absent());
}
 
Example 12
Source File: MetricEnabledWrapperStream.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
MetricEnabledWrapperStream(String id, long fileSize, ProtoConfigurableEntity.Context context, T stream) {
  super(stream);
  this.fileSize = fileSize;
  dataThroughputMeterForCurrentStream = new Meter();
  remainingBytesCounter = new Counter();
  sentBytesCounter = new Counter();
  remainingBytesCounter.inc(fileSize);
  FileRefUtil.initMetricsIfNeeded(context);
  dataTransferMeter = context.getMeter(FileRefUtil.TRANSFER_THROUGHPUT_METER);
  gaugeStatisticsMap =  context.getGauge(FileRefUtil.fileStatisticGaugeName(context)).getValue();
  completedFileCount = (long)gaugeStatisticsMap.get(FileRefUtil.COMPLETED_FILE_COUNT);
  //Shows the size of the file in the brack after the file name.
  gaugeStatisticsMap.put(FileRefUtil.FILE, String.format(FileRefUtil.BRACKETED_TEMPLATE, id, convertBytesToDisplayFormat(fileSize)));
}
 
Example 13
Source File: DynamicMetricsManager.java    From brooklin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Update the counter (or creates it if it does not exist) for the specified key/metricName pair by the given value.
 * To decrement the counter, pass in a negative value.
 * @param classSimpleName the simple name of the underlying class
 * @param key the key (i.e. topic or partition) for the metric
 * @param metricName the metric name
 * @param value amount to increment the counter by (use negative value to decrement)
 */
public void createOrUpdateCounter(String classSimpleName, String key, String metricName, long value) {
  validateArguments(classSimpleName, metricName);

  // create and register the metric if it does not exist
  Counter counter = (Counter) checkCache(classSimpleName, key, metricName).orElseGet(() -> {
    Counter newCounter = _metricRegistry.counter(MetricRegistry.name(classSimpleName, key, metricName));
    updateCache(classSimpleName, key, metricName, newCounter);
    return newCounter;
  });
  counter.inc(value);
}
 
Example 14
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected static void processCounter(@NotNull Counter counter, long delta) {
    if (delta > 0) {
        counter.inc(delta);
    }
    else if (delta < 0) {
        counter.dec(delta * -1);
    }
}
 
Example 15
Source File: CountedHandler.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Counter counter = metricRegistry.counter(counterName);
    counter.inc();

    try {
        routeHandler.handle(routeContext);
    } finally {
        if (isActive) {
            counter.dec();
        }
    }
}
 
Example 16
Source File: SubscriptionStreamController.java    From nakadi with MIT License 5 votes vote down vote up
private StreamingResponseBody stream(final String subscriptionId,
                                     final HttpServletRequest request,
                                     final HttpServletResponse response,
                                     final Client client,
                                     final StreamParameters streamParameters,
                                     final Span parentSubscriptionSpan) {
    final String flowId = FlowIdUtils.peek();

    return outputStream -> {
        FlowIdUtils.push(flowId);
        final String metricName = metricNameForSubscription(subscriptionId, CONSUMERS_COUNT_METRIC_NAME);
        final Counter consumerCounter = metricRegistry.counter(metricName);
        consumerCounter.inc();
        final AtomicBoolean connectionReady = closedConnectionsCrutch.listenForConnectionClose(request);
        SubscriptionStreamer streamer = null;
        final SubscriptionOutputImpl output = new SubscriptionOutputImpl(response, outputStream);
        try {
            if (eventStreamChecks.isSubscriptionConsumptionBlocked(subscriptionId, client.getClientId())) {
                writeProblemResponse(response, outputStream,
                        Problem.valueOf(FORBIDDEN, "Application or event type is blocked"));
                return;
            }
            final Subscription subscription = subscriptionDbRepository.getSubscription(subscriptionId);
            subscriptionValidationService.validatePartitionsToStream(subscription,
                    streamParameters.getPartitions());
            streamer = subscriptionStreamerFactory.build(subscription, streamParameters, output,
                    connectionReady, parentSubscriptionSpan, client.getClientId());
            streamer.stream();
        } catch (final InterruptedException ex) {
            LOG.warn("Interrupted while streaming with " + streamer, ex);
            Thread.currentThread().interrupt();
        } catch (final RuntimeException e) {
            output.onException(e);
        } finally {
            consumerCounter.dec();
            outputStream.close();
        }
    };
}
 
Example 17
Source File: TimelineRampFollowers.java    From socialite with Apache License 2.0 5 votes vote down vote up
@Override
public void runCommand(Namespace namespace) {

    this.getUserGraphService().removeUser(user.getUserId());

    // Create the user
    this.getUserGraphService().createUser(user);

    // Create all of the users they're going to follow
    for( int i = 0; i < namespace.getInt("stop"); i++ ) {
        this.getUserGraphService().getOrCreateUserById("toFollow"+i);
    }

    Counter counter = this.getCounter("count");
    counter.inc(namespace.getInt("start"));

    // prime the cache
    this.getFeedService().getFeedFor(user,TIMELINE_SIZE);

    // ramp up follower count and measure timeline read at each step
    for( int i = namespace.getInt("start"); i < namespace.getInt("stop"); i++  ) {

        // follow the user
        User toFollow = this.getUserGraphService().getOrCreateUserById("toFollow"+i);
        this.getUserGraphService().follow(user, toFollow);
        // send messages from the followed user
        for( int m = 0; m < 100; m++ ) {
            this.getFeedService().post( toFollow, ContentGenerator.newContent(toFollow) );
        }
        counter.inc();
        measureReadLatency();
    }
}
 
Example 18
Source File: CounterConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    counterConverter = new CounterConverter();
    SortedMap<String, Counter> counters = new TreeMap<>();
    Counter counter = new Counter();
    counters.put(COUNTER_METRIC, counter);
    counter.inc(METRIC_VALUE.intValue());
    metrics = counterConverter.convert(counters, currentTimeMillis);
}
 
Example 19
Source File: OutputStreamReporterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void testTags() throws IOException {
  MetricContext metricContext = MetricContext.builder(this.getClass().getCanonicalName()).build();
  Counter counter = metricContext.counter("com.linkedin.example.counter");

  Map<String, String> tags = new HashMap<>();
  tags.put("testKey", "testValue");
  tags.put("key2", "value2");

  OutputStreamReporter reporter =
      OutputStreamReporter.Factory.newBuilder().withTags(tags).outputTo(this.stream).build(new Properties());

  counter.inc();

  reporter.report();
  Assert.assertTrue(this.stream.toString().contains("key2=value2"));
  Assert.assertTrue(this.stream.toString().contains("testKey=testValue"));
  String[] lines = this.stream.toString().split("\n");

  Map<String, Set<String>> expected = new HashMap<>();

  expectMetrics(expected, lines);
  Set<String> counterSubMetrics = new HashSet<>();
  counterSubMetrics.add("count");
  expected.put("com.linkedin.example.counter", counterSubMetrics);

  reporter.close();

}
 
Example 20
Source File: TestKafkaUReplicatorMetricsReporter.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultConf() {

  KafkaUReplicatorMetricsReporter.init(null);
  Assert.assertNull(KafkaUReplicatorMetricsReporter.get().getRegistry());
  try {
    Field field = KafkaUReplicatorMetricsReporter.class.getDeclaredField("DID_INIT");
    field.setAccessible(true);
    field.set(KafkaUReplicatorMetricsReporter.get(), false);
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  MetricsReporterConf conf = new MetricsReporterConf("sjc1.sjc1a",
      Collections.singletonList("ureplicator-manager"), null, "localhost",
      4744);
  KafkaUReplicatorMetricsReporter.init(conf);
  Object firstInitInstance = KafkaUReplicatorMetricsReporter.get();
  // Double init will get same instance.
  KafkaUReplicatorMetricsReporter.init(conf);
  Object secondInitInstance = KafkaUReplicatorMetricsReporter.get();
  Assert.assertTrue(firstInitInstance == secondInitInstance);
  Counter testCounter0 = new Counter();
  Meter testMeter0 = new Meter();
  Timer testTimer0 = new Timer();
  KafkaUReplicatorMetricsReporter.get().registerMetric("testCounter0", testCounter0);
  KafkaUReplicatorMetricsReporter.get().registerMetric("testMeter0", testMeter0);
  KafkaUReplicatorMetricsReporter.get().registerMetric("testTimer0", testTimer0);

  testCounter0.inc();
  testMeter0.mark();
  Context context = testTimer0.time();
  context.stop();

  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getCounters().get("testCounter0")
          .getCount(),
      1);
  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getMeters().get("testMeter0")
          .getCount(),
      1);
  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getTimers().get("testTimer0")
          .getCount(),
      1);
}