Java Code Examples for io.micrometer.core.instrument.Counter#increment()

The following examples show how to use io.micrometer.core.instrument.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: MeteredScheduledThreadPoolExecutor.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@Override
protected void afterExecute(Runnable task, Throwable throwable) {
   Instant start = taskExecutionTimer.get();
   Timer timer = meterRegistry.timer(meterName("task.time"));
   timer.record(Duration.between(start, Instant.now()));

   super.afterExecute(task, throwable);
   if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) {
      try {
         ((Future<?>) task).get();
      } catch (CancellationException ce) {
         throwable = ce;
      } catch (ExecutionException ee) {
         throwable = ee.getCause();
      } catch (InterruptedException ie) {
         Thread.currentThread().interrupt();
      }
   }
   if (throwable != null) {
      Counter failedTasksCounter = meterRegistry.counter(meterName("failed.tasks"));
      failedTasksCounter.increment();
   } else {
      Counter successfulTasksCounter = meterRegistry.counter(meterName("successful.tasks"));
      successfulTasksCounter.increment();
   }
}
 
Example 2
Source File: AbstractElasticsearchMeterRegistryIntegrationTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void indexTemplateShouldApply() throws Throwable {
    String response = sendHttpGet(host);
    String versionNumber = JsonPath.parse(response).read("$.version.number");
    assertThat(versionNumber).isEqualTo(getVersion());

    Counter counter = registry.counter("test.counter");
    counter.increment();

    registry.publish();

    String indexName = registry.indexName();
    String mapping = sendHttpGet(host + "/" + indexName + "/_mapping");
    String countType = JsonPath.parse(mapping).read(getCountTypePath(indexName));
    assertThat(countType).isEqualTo("double");
}
 
Example 3
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
void receiveMetricsSuccessfully(StatsdProtocol protocol) throws InterruptedException {
    serverLatch = new CountDownLatch(3);
    server = startServer(protocol, 0);

    final int port = server.address().getPort();

    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    startRegistryAndWaitForClient();
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    counter.increment();
    counter.increment();
    counter.increment();
    assertThat(serverLatch.await(3, TimeUnit.SECONDS)).isTrue();
}
 
Example 4
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
@Issue("#1676")
void stopAndStartMeterRegistrySendsMetrics(StatsdProtocol protocol) throws InterruptedException {
    serverLatch = new CountDownLatch(3);
    server = startServer(protocol, 0);

    final int port = server.address().getPort();

    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    startRegistryAndWaitForClient();
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    counter.increment();
    await().until(() -> serverLatch.getCount() == 2);
    meterRegistry.stop();
    await().until(this::clientIsDisposed);
    // These increments shouldn't be sent
    IntStream.range(0, 3).forEach(i -> counter.increment());
    startRegistryAndWaitForClient();
    assertThat(serverLatch.getCount()).isEqualTo(2);
    counter.increment();
    counter.increment();
    assertThat(serverLatch.await(1, TimeUnit.SECONDS)).isTrue();
}
 
Example 5
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@Issue("#1676")
void stopAndStartMeterRegistryWithLineSink() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(3);
    meterRegistry = StatsdMeterRegistry.builder(StatsdConfig.DEFAULT).lineSink(s -> latch.countDown()).build();
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    counter.increment();
    meterRegistry.stop();
    // These increments shouldn't be processed
    IntStream.range(0, 3).forEach(i -> counter.increment());
    meterRegistry.start();
    assertThat(latch.getCount()).isEqualTo(2);
    counter.increment();
    counter.increment();
    assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue();
}
 
Example 6
Source File: SinkShim.java    From mewbase with MIT License 5 votes vote down vote up
@Override
public Long publishSync(String channelName, BsonObject event) {
    Long evtNum = impl.publishSync(channelName,event);
    Counter ctr = syncCounters.computeIfAbsent( channelName, s -> createCounter(SYNC,channelName));
    ctr.increment();
    return evtNum;
}
 
Example 7
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCounter_whenIncrement_thenValueChanged() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    Counter counter = Counter
      .builder("objects.instance")
      .description("indicates instance count of the object")
      .tags("dev", "performance")
      .register(registry);

    counter.increment(2.0);
    assertTrue(counter.count() == 2);

    counter.increment(-1);
    assertTrue(counter.count() == 2);
}
 
Example 8
Source File: EndToEndStatsTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public void merge(String streamSegmentName, long dataLength, int numOfEvents, long txnCreationTime) {
    Counter eventCounter = registry.counter(SEGMENT_WRITE_EVENTS, segmentTags(streamSegmentName));
    Counter byteCounter = registry.counter(SEGMENT_WRITE_BYTES, segmentTags(streamSegmentName));
    references.add(eventCounter);
    references.add(byteCounter);
    eventCounter.increment(numOfEvents);
    byteCounter.increment(dataLength);
}
 
Example 9
Source File: EndToEndStatsTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public void recordAppend(String streamSegmentName, long dataLength, int numOfEvents, Duration elapsed) {
    if (!NameUtils.isTransactionSegment(streamSegmentName)) {
        Counter eventCounter = registry.counter(SEGMENT_WRITE_EVENTS, segmentTags(streamSegmentName));
        Counter byteCounter = registry.counter(SEGMENT_WRITE_BYTES, segmentTags(streamSegmentName));
        references.add(eventCounter);
        references.add(byteCounter);
        eventCounter.increment(numOfEvents);
        byteCounter.increment(dataLength);
    }
}
 
Example 10
Source File: MicrometerHttpServerMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void incrementErrorsCount(SocketAddress remoteAddress, String uri) {
	Counter errors = errorsCache.computeIfAbsent(new MeterKey(uri, null, null, null),
			key -> filter(errorsBuilder.tags(URI, uri)
			                           .register(REGISTRY)));
	if (errors != null) {
		errors.increment();
	}
}
 
Example 11
Source File: MicrometerHttpMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void incrementErrorsCount(SocketAddress remoteAddress, String uri) {
	String address = Metrics.formatSocketAddress(remoteAddress);
	Counter errors = errorsCache.computeIfAbsent(new MeterKey(uri, address, null, null),
			key -> filter(errorsBuilder.tags(REMOTE_ADDRESS, address, URI, uri)
			                           .register(REGISTRY)));
	if (errors != null) {
		errors.increment();
	}
}
 
Example 12
Source File: MicrometerChannelMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void incrementErrorsCount(SocketAddress remoteAddress) {
	String address = reactor.netty.Metrics.formatSocketAddress(remoteAddress);
	Counter c = errorsCache.computeIfAbsent(address,
			key -> filter(errorCountBuilder.tag(REMOTE_ADDRESS, address)
			                               .register(REGISTRY)));
	if (c != null) {
		c.increment();
	}
}
 
Example 13
Source File: SinkShim.java    From mewbase with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Long> publishAsync(String channelName, BsonObject event) {
    CompletableFuture<Long> evtFut = impl.publishAsync(channelName,event);
    Counter ctr = asyncCounters.computeIfAbsent(channelName, s -> createCounter(ASYNC,channelName));
    ctr.increment();
    return evtFut;
}
 
Example 14
Source File: QueueCounter.java    From rqueue with Apache License 2.0 5 votes vote down vote up
private void updateCounter(Map<String, Counter> map, String queueName) {
  Counter counter = map.get(queueName);
  if (counter == null) {
    return;
  }
  counter.increment();
}
 
Example 15
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
void whenBackendInitiallyDown_metricsSentAfterBackendStarts(StatsdProtocol protocol) throws InterruptedException {
    AtomicInteger writeCount = new AtomicInteger();
    serverLatch = new CountDownLatch(3);
    // start server to secure an open port
    server = startServer(protocol, 0);
    final int port = server.address().getPort();
    server.disposeNow();
    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    meterRegistry.start();
    trackWritesForUdpClient(protocol, writeCount);
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    IntStream.range(1, 4).forEach(counter::increment);
    if (protocol == StatsdProtocol.UDP) {
        await().until(() -> writeCount.get() == 3);
    }
    server = startServer(protocol, port);
    if (protocol == StatsdProtocol.TCP) {
        // client is null until TcpClient first connects
        await().until(() -> meterRegistry.client.get() != null);
        // TcpClient may take some time to reconnect to the server
        await().until(() -> !clientIsDisposed());
    }
    assertThat(serverLatch.getCount()).isEqualTo(3);

    if (protocol == StatsdProtocol.UDP) {
        // Note that this guarantees this test to be passed.
        // For UDP, the first change seems to be lost frequently somehow.
        Counter.builder("another.counter").register(meterRegistry).increment();
    }

    counter.increment();
    counter.increment();
    counter.increment();
    assertThat(serverLatch.await(1, TimeUnit.SECONDS)).isTrue();
}
 
Example 16
Source File: CounterTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("increment by a non-negative amount")
default void incrementAmount(MeterRegistry registry) {
    Counter c = registry.counter("myCounter");
    c.increment(2);
    c.increment(0);
    clock(registry).add(step());

    assertEquals(2L, c.count());
}
 
Example 17
Source File: CounterTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@DisplayName("multiple increments are maintained")
@Test
default void increment(MeterRegistry registry) {
    Counter c = registry.counter("myCounter");
    c.increment();
    clock(registry).add(step());
    assertThat(c.count()).isEqualTo(1.0, offset(1e-12));
    c.increment();
    c.increment();
    clock(registry).add(step());

    // in the case of a step aggregating system will be 2, otherwise 3
    assertThat(c.count()).isGreaterThanOrEqualTo(2.0);
}
 
Example 18
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
void resumeSendingMetrics_whenServerIntermittentlyFails(StatsdProtocol protocol) throws InterruptedException {
    serverLatch = new CountDownLatch(1);
    AtomicInteger writeCount = new AtomicInteger();
    server = startServer(protocol, 0);

    final int port = server.address().getPort();

    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    startRegistryAndWaitForClient();
    trackWritesForUdpClient(protocol, writeCount);
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    counter.increment(1);
    assertThat(serverLatch.await(5, TimeUnit.SECONDS)).isTrue();

    Disposable firstClient = meterRegistry.client.get();

    server.disposeNow();
    serverLatch = new CountDownLatch(3);
    // client will try to send but server is down
    IntStream.range(2, 5).forEach(counter::increment);
    if (protocol == StatsdProtocol.UDP) {
        await().until(() -> writeCount.get() == 4);
    }
    server = startServer(protocol, port);
    assertThat(serverLatch.getCount()).isEqualTo(3);

    await().until(() -> bound);

    // Note that this guarantees this test to be passed.
    // For TCP, this will help trigger replacing client. If this triggered replacing, this change will be lost.
    // For UDP, the first change seems to be lost frequently somehow.
    Counter.builder("another.counter").register(meterRegistry).increment();

    if (protocol == StatsdProtocol.TCP) {
        await().until(() -> meterRegistry.client.get() != firstClient);
    }

    counter.increment(5);
    counter.increment(6);
    counter.increment(7);
    assertThat(serverLatch.await(3, TimeUnit.SECONDS)).isTrue();
}
 
Example 19
Source File: AbstractMetricService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
protected void incrementMetricCounter(String metric, String... tags) {
    Counter counter = Metrics.counter(metric, tags);
    counter.increment();
}
 
Example 20
Source File: Main.java    From blog-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    MeterRegistry registry = new JmxMeterRegistry(new JmxConfig() {
        @Override
        public Duration step() {
            return Duration.ofSeconds(1);
        }

        @Override
        public String get(String s) {
            return null;
        }
    }, Clock.SYSTEM);

    Counter counter = Counter
            .builder("my.counter")
            .description("counts something important")
            .tag("environment", "test")
            .tag("region", "us-east")
            .register(registry);

    counter.increment();
    counter.increment(2.5);

    Timer timer = Timer.builder("my.timer").register(registry);

    timer.record(() -> {
        System.out.println("sleeping");
        try {
            Thread.sleep(550);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    timer.record(Duration.ofMillis(3));

    // Wait some time before application exit
    // This gives some time to use JConsole to connect to the
    // application and inspect the metrics
    System.out.println("Keeping application alive");
    Thread.sleep(240000);
    System.out.println("done");
}