Java Code Examples for com.netflix.spectator.api.Counter#increment()

The following examples show how to use com.netflix.spectator.api.Counter#increment() . 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: ActionMetrics.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public void failure(long startTime, Throwable error) {
    lastCompletionRef.set(registry.clock().wallTime());
    if (startTime >= 0) {
        latencyTimerOnError.record(registry.clock().wallTime() - startTime, TimeUnit.MILLISECONDS);
    }

    Counter exceptionCounter = exceptionCounters.get(error.getClass());
    if (exceptionCounter == null) {
        Id errorId = registry.createId(root, commonTags)
                .withTag("status", "failure")
                .withTag("exception", error.getClass().getSimpleName());
        exceptionCounter = registry.counter(errorId);
        exceptionCounters.put(error.getClass(), exceptionCounter);
    }
    exceptionCounter.increment();
}
 
Example 2
Source File: DefaultPlaceholderCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncrement() {
  String[] tagValue = new String[] { "default" };
  Counter c = factory.counter(factory.createId("testIncrement",
          Collections.singleton(new TestTagFactory(tagValue))));
  Assertions.assertEquals(0L, c.count());
  Assertions.assertEquals("testIncrement:tag=default", c.id().toString());
  c.increment();
  Assertions.assertEquals(1L, c.count());
  c.increment();
  c.increment();
  Assertions.assertEquals(3L, c.count());

  tagValue[0] = "value2";
  Assertions.assertEquals("testIncrement:tag=value2", c.id().toString());
  c.increment();
  Assertions.assertEquals(1L, c.count());

  tagValue[0] = "default";
  Assertions.assertEquals("testIncrement:tag=default", c.id().toString());
  c.increment();
  Assertions.assertEquals(4L, c.count());
}
 
Example 3
Source File: ServoCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void expiration() {
  final long initTime = TimeUnit.MINUTES.toMillis(30);
  final long fifteenMinutes = TimeUnit.MINUTES.toMillis(15);

  // Not expired on init, wait for activity to mark as active
  clock.setWallTime(initTime);
  Counter c = newCounter("foo");
  Assertions.assertFalse(c.hasExpired());
  c.increment(42);
  Assertions.assertFalse(c.hasExpired());

  // Expires with inactivity, total count in memory is maintained
  clock.setWallTime(initTime + fifteenMinutes);
  Assertions.assertFalse(c.hasExpired());

  // Expires with inactivity, total count in memory is maintained
  clock.setWallTime(initTime + fifteenMinutes + 1);
  Assertions.assertEquals(c.count(), 42);
  Assertions.assertTrue(c.hasExpired());

  // Activity brings it back
  c.increment();
  Assertions.assertEquals(c.count(), 43);
  Assertions.assertFalse(c.hasExpired());
}
 
Example 4
Source File: ServoRegistryTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void resurrectExpiredAndIncrement() {
  ManualClock clock = new ManualClock();
  ServoRegistry registry = Servo.newRegistry(clock);
  Counter c = registry.counter("test");

  clock.setWallTime(60000 * 30);
  registry.getMonitors();

  Assertions.assertTrue(c.hasExpired());

  c.increment();
  Assertions.assertEquals(1, c.count());
  Assertions.assertEquals(1, registry.counter("test").count());

  clock.setWallTime(60000 * 60);
  registry.getMonitors();

  Assertions.assertTrue(c.hasExpired());

  c.increment();
  Assertions.assertEquals(1, c.count());
  Assertions.assertEquals(1, registry.counter("test").count());
}
 
Example 5
Source File: Scheduler.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Update the next execution time based on the options for this task.
 *
 * @param skipped
 *     Counter that will be incremented each time an expected execution is
 *     skipped when using {@link Policy#FIXED_RATE_SKIP_IF_LONG}.
 */
void updateNextExecutionTime(Counter skipped) {
  switch (options.schedulingPolicy) {
    case FIXED_DELAY:
      nextExecutionTime = clock.wallTime() + options.frequencyMillis;
      break;
    case FIXED_RATE_SKIP_IF_LONG:
      final long now = clock.wallTime();
      nextExecutionTime += options.frequencyMillis;
      while (nextExecutionTime < now) {
        nextExecutionTime += options.frequencyMillis;
        skipped.increment();
      }
      break;
    default:
      break;
  }
}
 
Example 6
Source File: DefaultPlaceholderCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
private void doMeasurementTest(Counter c, int expectedValue, long expectedTime) {
  c.increment(expectedValue);
  clock.setWallTime(expectedTime);
  List<Measurement> measurements = Utils.toList(c.measure());

  Assertions.assertEquals(1, measurements.size());

  Measurement m = measurements.get(0);
  Assertions.assertEquals(c.id(), m.id());
  Assertions.assertEquals(expectedTime, m.timestamp());
  Assertions.assertEquals(expectedValue, m.value(), 0.1e-12);
}
 
Example 7
Source File: TestPrometheusPublisher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void collect() throws IllegalAccessException, IOException {
  new Expectations(RegistrationManager.INSTANCE) {
    {
      RegistrationManager.INSTANCE.getAppId();
      result = "testAppId";
    }
  };
  ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:0");
  publisher.init(globalRegistry, null, null);

  Registry registry = new DefaultRegistry(new ManualClock());
  globalRegistry.add(registry);

  Counter counter = registry.counter("count.name", "tag1", "tag1v", "tag2", "tag2v");
  counter.increment();

  HTTPServer httpServer = (HTTPServer) FieldUtils.readField(publisher, "httpServer", true);
  com.sun.net.httpserver.HttpServer server = (HttpServer) FieldUtils.readField(httpServer, "server", true);

  URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/metrics");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  try (InputStream is = conn.getInputStream()) {
    Assert.assertEquals("# HELP ServiceComb_Metrics ServiceComb Metrics\n" +
            "# TYPE ServiceComb_Metrics untyped\n" +
            "count_name{appId=\"testAppId\",tag1=\"tag1v\",tag2=\"tag2v\",} 1.0\n",
        IOUtils.toString(is, StandardCharsets.UTF_8));
  }

  publisher.destroy();
}
 
Example 8
Source File: DefaultPlaceholderCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrementAmount() {
  String[] tagValue = new String[] { "default" };
  Counter c = factory.counter(factory.createId("testIncrementAmount",
          Collections.singleton(new TestTagFactory(tagValue))));

  c.increment(42);
  Assertions.assertEquals(42L, c.count());

  tagValue[0] = "value2";
  c.increment(54);
  Assertions.assertEquals(54L, c.count());
}
 
Example 9
Source File: MetricsControllerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeSimpleRegistry() {
  DefaultRegistry registry = new DefaultRegistry(clock);
  Counter counterA = registry.counter(idAXY);
  Counter counterB = registry.counter(idBXY);
  counterA.increment(4);
  counterB.increment(10);

  List<TaggedDataPoints> expectedTaggedDataPointsA
    = Arrays.asList(
        new TaggedDataPoints(
            Arrays.asList(new BasicTag("tagA", "X"),
                          new BasicTag("tagB", "Y")),
            Arrays.asList(new DataPoint(clock.wallTime(), 4))));

  List<TaggedDataPoints> expectedTaggedDataPointsB
    = Arrays.asList(
        new TaggedDataPoints(
            Arrays.asList(new BasicTag("tagA", "X"),
                          new BasicTag("tagB", "Y")),
            Arrays.asList(new DataPoint(clock.wallTime(), 10))));

  HashMap<String, MetricValues> expect = new HashMap<>();
  expect.put("idA", new MetricValues("Counter", expectedTaggedDataPointsA));
  expect.put("idB", new MetricValues("Counter", expectedTaggedDataPointsB));
  Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
 
Example 10
Source File: IntervalCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasure() {
  Registry r = new DefaultRegistry(clock);
  clock.setWallTime(61000L);
  Id id = r.createId("test");
  Counter c = IntervalCounter.get(r, id);

  // all meters should have the correct timestamp
  r.stream().forEach(meter -> {
    for (Measurement m : meter.measure()) {
      Assertions.assertEquals(m.timestamp(), 61000L);
    }
  });

  final List<Measurement> measurements = getAllMeasurements(r);
  final double initAge = Utils.first(measurements, Statistic.duration).value();
  final double initCount = Utils.first(measurements, Statistic.count).value();
  Assertions.assertEquals(61.0, initAge, EPSILON);
  Assertions.assertEquals(0.0, initCount, EPSILON);

  clock.setWallTime(120000L);
  c.increment();
  final List<Measurement> afterMeasurements = getAllMeasurements(r);
  final double afterAge = Utils.first(afterMeasurements, Statistic.duration).value();
  final double afterCount = Utils.first(afterMeasurements, Statistic.count).value();
  Assertions.assertEquals(0.0, afterAge, EPSILON);
  Assertions.assertEquals(1.0, afterCount, EPSILON);
}
 
Example 11
Source File: PolledMeter.java    From spectator with Apache License 2.0 5 votes vote down vote up
private void update(Counter counter) {
  T obj = ref.get();
  if (obj != null) {
    long current = f.applyAsLong(obj);
    if (current > previous) {
      final long delta = current - previous;
      LOGGER.trace("incrementing counter [{}] by {}", counter.id(), delta);
      counter.increment(delta);
    } else {
      LOGGER.trace("no update to counter [{}]: previous = {}, current = {}",
          counter.id(), previous, current);
    }
    previous = current;
  }
}
 
Example 12
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void counterGet() {
  Counter c1 = registry.counter("foo");
  c1.increment();

  Counter c2 = (Counter) registry.get(registry.createId("foo"));
  Assertions.assertEquals(1, c2.count());
}
 
Example 13
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void counterWithTags() {
  Counter c1 = registry.counter("foo", "a", "1", "b", "2");
  c1.increment();

  Counter c2 = registry.counter(registry.createId("foo", "a", "1", "b", "2"));
  Assertions.assertEquals(1, c2.count());
}
 
Example 14
Source File: ServoCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testInit() {
  Counter c = newCounter("foo");
  Assertions.assertEquals(c.count(), 0L);
  c.increment();
  Assertions.assertEquals(c.count(), 1L);
}
 
Example 15
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void counterIncrement() {
  Counter c = registry.counter("foo");
  Assertions.assertEquals(0, c.count());
  c.increment();
  Assertions.assertEquals(1, c.count());
}
 
Example 16
Source File: RxEventBusMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
void delivered(long queueSize, Object event, long latency) {
    queueSizeGauge.set(queueSize);
    latencyGauge.set(latency);
    Counter counter = eventCounters.computeIfAbsent(
            event.getClass(),
            c -> registry.counter(eventCounterId.withTag("class", c.getName()))
    );
    counter.increment();
}
 
Example 17
Source File: RxEventBusMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
void published(Object event) {
    Counter counter = eventCounters.computeIfAbsent(
            event.getClass(),
            c -> registry.counter(eventCounterId.withTag("class", c.getName()))
    );
    counter.increment();
}
 
Example 18
Source File: ExecutionMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public void failure(Throwable error) {
    Counter exceptionCounter = exceptionCounters.get(error.getClass());
    if (exceptionCounter == null) {
        Id errorId = registry.createId(root, commonTags).withTag("exception", error.getClass().getSimpleName());
        exceptionCounter = registry.counter(errorId);
        exceptionCounters.put(error.getClass(), exceptionCounter);
    }

    errorCounter.increment();
    exceptionCounter.increment();
}
 
Example 19
Source File: ThreadPoolMonitor.java    From spectator with Apache License 2.0 4 votes vote down vote up
/**
 * Register the provided thread pool, optionally tagged with a name. If a custom
 * {@link RejectedExecutionHandler} is going to be used, then it should be set on the pool
 * prior to attaching. Otherwise it will overwrite the wrapped rejection handler used to
 * track the number of rejected tasks from this pool.
 *
 * @param registry
 *     The registry to use.
 * @param threadPool
 *     The thread pool to monitor.
 * @param threadPoolName
 *     A name with which to tag the metrics (default name used if {@code null} or empty).
 */
public static void attach(
    final Registry registry,
    final ThreadPoolExecutor threadPool,
    final String threadPoolName) {

  Preconditions.checkNotNull(registry, "registry");
  Preconditions.checkNotNull(threadPool, "threadPool");

  final String idValue;
  if (threadPoolName == null || threadPoolName.isEmpty()) {
    idValue = DEFAULT_ID;
  } else {
    idValue = threadPoolName;
  }

  final Tag idTag = new BasicTag(ID_TAG_NAME, idValue);

  PolledMeter.using(registry)
      .withName(TASK_COUNT)
      .withTag(idTag)
      .monitorMonotonicCounter(threadPool, ThreadPoolExecutor::getTaskCount);
  PolledMeter.using(registry)
      .withName(COMPLETED_TASK_COUNT)
      .withTag(idTag)
      .monitorMonotonicCounter(threadPool, ThreadPoolExecutor::getCompletedTaskCount);
  PolledMeter.using(registry)
      .withName(CURRENT_THREADS_BUSY)
      .withTag(idTag)
      .monitorValue(threadPool, ThreadPoolExecutor::getActiveCount);
  PolledMeter.using(registry)
      .withName(MAX_THREADS)
      .withTag(idTag)
      .monitorValue(threadPool, ThreadPoolExecutor::getMaximumPoolSize);
  PolledMeter.using(registry)
      .withName(POOL_SIZE)
      .withTag(idTag)
      .monitorValue(threadPool, ThreadPoolExecutor::getPoolSize);
  PolledMeter.using(registry)
      .withName(CORE_POOL_SIZE)
      .withTag(idTag)
      .monitorValue(threadPool, ThreadPoolExecutor::getCorePoolSize);
  PolledMeter.using(registry)
      .withName(QUEUE_SIZE)
      .withTag(idTag)
      .monitorValue(threadPool, tp -> tp.getQueue().size());

  // Handler is not allowed to be null, checked internally to thread pool
  Counter rejected = registry.counter(registry.createId(REJECTED_TASK_COUNT).withTag(idTag));
  RejectedExecutionHandler handler = threadPool.getRejectedExecutionHandler();
  RejectedExecutionHandler monitoredHandler = (Runnable r, ThreadPoolExecutor exec) -> {
    rejected.increment();
    handler.rejectedExecution(r, exec);
  };
  threadPool.setRejectedExecutionHandler(monitoredHandler);
}
 
Example 20
Source File: Counters.java    From spectator with Apache License 2.0 4 votes vote down vote up
private long incrementAndGet(Counter c) {
  c.increment();
  return c.count();
}