io.micrometer.core.instrument.Counter Java Examples

The following examples show how to use io.micrometer.core.instrument.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: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenDistributionSummary_whenEnrichWithHistograms_thenDataAggregated() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    DistributionSummary hist = DistributionSummary
      .builder("summary")
      .histogram(Histogram.linear(0, 10, 5))
      .register(registry);

    hist.record(3);
    hist.record(8);
    hist.record(20);
    hist.record(40);
    hist.record(13);
    hist.record(26);

    Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);

    assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0)));
}
 
Example #2
Source File: WorkspaceSuccessfulStartAttemptsMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldCollectOnlyStarted() {
  // given
  WorkspaceSuccessfulStartAttemptsMeterBinder meterBinder =
      new WorkspaceSuccessfulStartAttemptsMeterBinder(eventService);
  meterBinder.bindTo(registry);

  // when
  eventService.publish(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(WorkspaceStatus.STARTING)
          .withStatus(WorkspaceStatus.RUNNING)
          .withWorkspaceId("id1"));
  // then
  Counter successful = registry.find("che.workspace.started.total").counter();
  Assert.assertEquals(successful.count(), 1.0);
}
 
Example #3
Source File: SkywalkingCounterTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void testCounter() {
    // Creating a simplify micrometer counter
    final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
    Counter counter = registry.counter("test_counter", "skywalking", "test");

    // Check Skywalking counter type
    Assert.assertTrue(counter instanceof SkywalkingCounter);
    final SkywalkingCounter skywalkingCounter = (SkywalkingCounter) counter;
    final org.apache.skywalking.apm.toolkit.meter.Counter realCounter =
        Whitebox.getInternalState(skywalkingCounter, "counter");

    final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));

    // Simplify increment
    skywalkingCounter.increment(1d);
    assertCounter(realCounter, "test_counter", tags, 1);
    Assert.assertEquals(1d, skywalkingCounter.count(), 0.0);

    // Multiple increment
    skywalkingCounter.increment(2d);
    skywalkingCounter.increment(3d);
    assertCounter(realCounter, "test_counter", tags, 6);
    Assert.assertEquals(6d, skywalkingCounter.count(), 0.0);
}
 
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: WorkspaceFailureMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(dataProvider = "failureWhileInStatus")
public void shouldCollectFailureCountsPerStatus(WorkspaceStatus failureStatus) {
  events.onEvent(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(failureStatus)
          .withStatus(WorkspaceStatus.STOPPED)
          .withError("D'oh!")
          .withWorkspaceId("1"));

  List<Counter> restOfCounters = new ArrayList<>(failureCounters);

  Counter counter =
      failureCounters
          .stream()
          .filter(c -> failureStatus.name().equals(c.getId().getTag("while")))
          .findAny()
          .orElseThrow(
              () ->
                  new AssertionError(
                      "Could not find a counter for failure status " + failureStatus));

  restOfCounters.remove(counter);

  assertEquals(counter.count(), 1d);
  restOfCounters.forEach(c -> assertEquals(c.count(), 0d));
}
 
Example #6
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
void whenRegistryStopped_doNotConnectToBackend(StatsdProtocol protocol) throws InterruptedException {
    serverLatch = new CountDownLatch(3);
    // start server to secure an open port
    server = startServer(protocol, 0);
    final int port = server.address().getPort();
    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    startRegistryAndWaitForClient();
    server.disposeNow();
    meterRegistry.stop();
    await().until(this::clientIsDisposed);
    server = startServer(protocol, port);
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    IntStream.range(0, 100).forEach(counter::increment);
    assertThat(serverLatch.await(1, TimeUnit.SECONDS)).isFalse();
}
 
Example #7
Source File: WorkspaceStartAttemptsMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldCollectOnlyStart() {
  // given
  WorkspaceStartAttemptsMeterBinder meterBinder =
      new WorkspaceStartAttemptsMeterBinder(eventService);
  meterBinder.bindTo(registry);

  // when
  eventService.publish(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(WorkspaceStatus.STOPPED)
          .withStatus(WorkspaceStatus.STARTING)
          .withWorkspaceId("id1"));
  // then
  Counter successful =
      registry.find("che.workspace.starting_attempts.total").tag("debug", "false").counter();
  Assert.assertEquals(successful.count(), 1.0);

  Counter debug =
      registry.find("che.workspace.starting_attempts.total").tag("debug", "true").counter();
  Assert.assertEquals(debug.count(), 0.0);
}
 
Example #8
Source File: WorkspaceStartAttemptsMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNotCollectDebugStartWhenSetToFalse() {
  // given
  WorkspaceStartAttemptsMeterBinder meterBinder =
      new WorkspaceStartAttemptsMeterBinder(eventService);
  meterBinder.bindTo(registry);

  // when
  eventService.publish(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(WorkspaceStatus.STOPPED)
          .withStatus(WorkspaceStatus.STARTING)
          .withWorkspaceId("id1")
          .withOptions(singletonMap(Constants.DEBUG_WORKSPACE_START, Boolean.FALSE.toString())));

  // then
  Counter successful =
      registry.find("che.workspace.starting_attempts.total").tag("debug", "false").counter();
  Assert.assertEquals(successful.count(), 1.0);

  Counter debug =
      registry.find("che.workspace.starting_attempts.total").tag("debug", "true").counter();
  Assert.assertEquals(debug.count(), 0.0);
}
 
Example #9
Source File: FluxMetricsTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void malformedOnNext() {
	TestPublisher<Integer> testPublisher = TestPublisher.createNoncompliant(CLEANUP_ON_TERMINATE);
	Flux<Integer> source = testPublisher.flux().hide();

	new FluxMetrics<>(source, registry)
			.subscribe();

	testPublisher.next(1)
	             .complete()
	             .next(2);

	Counter malformedMeter = registry
			.find(METER_MALFORMED)
			.counter();

	assertThat(malformedMeter).isNotNull();
	assertThat(malformedMeter.count()).isEqualTo(1);
}
 
Example #10
Source File: WorkspaceSuccessfulStartAttemptsMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(dataProvider = "allStatusTransitionsWithoutRunning")
public void shouldNotCollectEvents(WorkspaceStatus from, WorkspaceStatus to) {
  // given
  WorkspaceSuccessfulStartAttemptsMeterBinder meterBinder =
      new WorkspaceSuccessfulStartAttemptsMeterBinder(eventService);
  meterBinder.bindTo(registry);

  // when

  eventService.publish(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(from)
          .withStatus(to)
          .withWorkspaceId("id1"));

  // then
  Counter successful = registry.find("che.workspace.started.total").counter();
  Assert.assertEquals(successful.count(), 0.0);
}
 
Example #11
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimer_whenEnrichWithTimescaleHistogram_thenTimeScaleDataCollected() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    Timer timer = Timer
      .builder("timer")
      .histogram(Histogram.linearTime(TimeUnit.MILLISECONDS, 0, 200, 3))
      .register(registry);

    timer.record(1000, TimeUnit.MILLISECONDS);
    timer.record(23, TimeUnit.MILLISECONDS);
    timer.record(450, TimeUnit.MILLISECONDS);
    timer.record(341, TimeUnit.MILLISECONDS);
    timer.record(500, TimeUnit.MILLISECONDS);

    Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);

    assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3)));

}
 
Example #12
Source File: CountedAspectTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void countedWithFailure() {
    try {
        countedService.fail();
    } catch (Exception ignored) {
    }

    Counter counter = meterRegistry.get("metric.failing")
            .tag("method", "fail")
            .tag("class", "io.micrometer.core.aop.CountedAspectTest$CountedService")
            .tag("exception", "RuntimeException")
            .tag("result", "failure").counter();

    assertThat(counter.count()).isOne();
    assertThat(counter.getId().getDescription()).isEqualTo("To record something");
}
 
Example #13
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 #14
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenGlobalRegistry_whenIncrementAnywhere_thenCounted() {
    class CountedObject {
        private CountedObject() {
            Metrics
              .counter("objects.instance")
              .increment(1.0);
        }
    }
    Metrics.addRegistry(new SimpleMeterRegistry());

    Metrics
      .counter("objects.instance")
      .increment();
    new CountedObject();

    Optional<Counter> counterOptional = Metrics.globalRegistry
      .find("objects.instance")
      .counter();

    assertTrue(counterOptional.isPresent());
    assertTrue(counterOptional
      .get()
      .count() == 2.0);
}
 
Example #15
Source File: SecurityMetricsTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testName() throws Exception {
  Counter counter = mock(Counter.class);
  doReturn(counter).when(registry).counter(eq("counterName"), any(Iterable.class));

  underTest.increment("road", AUTHENTICATED, AUTHORISED);

  ArgumentCaptor<Iterable<Tag>> captor = ArgumentCaptor.forClass(Iterable.class);
  verify(registry).counter(eq("counterName"), captor.capture());
  verify(counter).increment();

  Iterable<Tag> tags = captor.getValue();
  assertThat(tags, hasItems(Tag.of("road", "road"), Tag.of("authentication", "AUTHENTICATED"),
      Tag.of("authorisation", "AUTHORISED")));
}
 
Example #16
Source File: TelegrafStatsdLineBuilderTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Issue("#644")
@Test
void escapeCharactersForTelegraf() {
    Counter c = registry.counter("hikari.pools", "pool", "poolname = abc,::hikari");
    TelegrafStatsdLineBuilder lineBuilder = new TelegrafStatsdLineBuilder(c.getId(), registry.config());
    assertThat(lineBuilder.count(1, Statistic.COUNT)).isEqualTo("hikari_pools,statistic=count,pool=poolname_=_abc___hikari:1|c");
}
 
Example #17
Source File: TaggedTimeLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void failedCounterIsRegistered() {
    Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters();
    timeLimiter.onError(new RuntimeException());

    Optional<Counter> failed = findMeterByKindAndNameTags(counters, "failed",
        timeLimiter.getName());
    assertThat(failed).map(Counter::count).contains(1d);
}
 
Example #18
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 #19
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 #20
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 #21
Source File: OfframpMetricsTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void markCommit() throws Exception {
  Counter commitSuccessCounter = registry.counter(OFFRAMP + COMMIT_SUCCESS, ROAD_STREAM_TAGS);
  Counter commitFailureCounter = registry.counter(OFFRAMP + COMMIT_FAILURE, ROAD_STREAM_TAGS);

  underTest = new StreamMetrics.Factory(pool, clock).create(ROAD_NAME, STREAM_NAME);

  underTest.markCommit(true);
  assertThat(commitSuccessCounter.count(), is(1.0));

  underTest.markCommit(false);
  assertThat(commitFailureCounter.count(), is(1.0));
}
 
Example #22
Source File: SysdigStatsdLineBuilderTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Issue("#739")
@Test
void sanitizeColons() {
    Counter c = registry.counter("my:counter", "my:tag", "my:value");
    SysdigStatsdLineBuilder lb = new SysdigStatsdLineBuilder(c.getId(), registry.config());

    registry.config().namingConvention(NamingConvention.dot);
    assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my_counter#statistic=count,my_tag=my_value:1|c");
}
 
Example #23
Source File: MetricsFuseableConditionalSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
MetricsFuseableConditionalSubscriber(
    ConditionalSubscriber<? super T> actual,
    Counter next,
    Counter complete,
    Counter error,
    Counter cancelled,
    Timer timer) {
  this.actual = actual;
  this.next = next;
  this.complete = complete;
  this.error = error;
  this.cancelled = cancelled;
  this.timer = timer;
}
 
Example #24
Source File: TaggedTimeLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timoutCounterIsRegistered() {
    Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters();
    timeLimiter.onError(new TimeoutException());

    Optional<Counter> timeout = findMeterByKindAndNameTags(counters, "timeout",
        timeLimiter.getName());
    assertThat(timeout).map(Counter::count).contains(1d);
}
 
Example #25
Source File: MetricCollectingClientCallListener.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Creates a new delegating ClientCallListener that will wrap the given client call listener to collect metrics.
 *
 * @param delegate The original call to wrap.
 * @param registry The registry to save the metrics to.
 * @param responseCounter The counter for incoming responses.
 * @param timerFunction A function that will return a timer for a given status code.
 */
public MetricCollectingClientCallListener(
        final ClientCall.Listener<A> delegate,
        final MeterRegistry registry,
        final Counter responseCounter,
        final Function<Code, Timer> timerFunction) {
    super(delegate);
    this.responseCounter = responseCounter;
    this.timerFunction = timerFunction;
    this.timerSample = Timer.start(registry);
}
 
Example #26
Source File: MetricCollectingClientInterceptor.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
protected Counter newResponseCounterFor(final MethodDescriptor<?, ?> method) {
    return this.counterCustomizer.apply(
            prepareCounterFor(method,
                    METRIC_NAME_CLIENT_RESPONSES_RECEIVED,
                    "The total number of responses received"))
            .register(this.registry);
}
 
Example #27
Source File: KafkaConsumerLoop.java    From pitchfork with Apache License 2.0 5 votes vote down vote up
public KafkaConsumerLoop(KafkaIngressConfigProperties properties,
                         Fork fork,
                         SpanValidator validator,
                         SpanBytesDecoder decoder,
                         Counter spansCounter,
                         MeterRegistry meterRegistry) {
    this.fork = fork;
    this.properties = properties;
    this.validator = validator;
    this.decoder = decoder;
    this.spansCounter = spansCounter;
    this.meterRegistry = meterRegistry;
}
 
Example #28
Source File: UdpMetricsTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void checkCounter(String name, String[] tags, boolean exists) {
	Counter counter = registry.find(name).tags(tags).counter();
	if (exists) {
		assertNotNull(counter);
		assertEquals(0, counter.count(), 0.0);
	}
	else {
		assertNull(counter);
	}
}
 
Example #29
Source File: OfframpMetricsTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void markRebalance() throws Exception {
  Counter rebalanceCounter = registry.counter(OFFRAMP + REBALANCE, ROAD_STREAM_TAGS);

  underTest = new StreamMetrics.Factory(pool, clock).create(ROAD_NAME, STREAM_NAME);
  underTest.markRebalance();

  assertThat(rebalanceCounter.count(), is(1.0));
}
 
Example #30
Source File: TaggedTimeLimiterMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timoutCounterIsRegistered() {
    Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters();
    timeLimiter.onError(new TimeoutException());

    Optional<Counter> timeout = findMeterByKindAndNameTags(counters, "timeout",
        timeLimiter.getName());
    assertThat(timeout).map(Counter::count).contains(1d);
}