io.micrometer.core.instrument.Gauge Java Examples

The following examples show how to use io.micrometer.core.instrument.Gauge. 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: ClassLoaderMetrics.java    From micrometer with Apache License 2.0 8 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();

    Gauge.builder("jvm.classes.loaded", classLoadingBean, ClassLoadingMXBean::getLoadedClassCount)
            .tags(tags)
            .description("The number of classes that are currently loaded in the Java virtual machine")
            .baseUnit(BaseUnits.CLASSES)
            .register(registry);

    FunctionCounter.builder("jvm.classes.unloaded", classLoadingBean, ClassLoadingMXBean::getUnloadedClassCount)
            .tags(tags)
            .description("The total number of classes unloaded since the Java virtual machine has started execution")
            .baseUnit(BaseUnits.CLASSES)
            .register(registry);
}
 
Example #2
Source File: BatchMetricsFlatFileToDbIntegrationTest.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunFlatFileToDbSkipJob_SkipInProcess_Failed() throws InterruptedException {
	JobExecution jobExecution = runJob("flatFileToDbSkipJob",
			"metrics/flatFileToDbSkipJob_SkipInProcess_Failed.csv");
	assertThat(jobExecution.getStatus(), is(BatchStatus.FAILED));
	ExecutionContext executionContext = jobExecution.getStepExecutions().iterator().next().getExecutionContext();
	long writeCount = 7L;
	MetricValidator validator = MetricValidatorBuilder.metricValidator().withExecutionContext(executionContext)
			.withBeforeChunkCount(3L).withStreamOpenCount(1L).withStreamUpdateCount(4L).withStreamCloseCount(0L)
			.withBeforeReadCount(12L).withReadCount(12L).withAfterReadCount(12L).withReadErrorCount(0L)
			.withBeforeProcessCount(7L).withProcessCount(7L).withAfterProcessCount(7L).withProcessErrorCount(5L)
			.withBeforeWriteCount(7L).withWriteCount(writeCount).withAfterWriteCount(7L).withAfterChunkCount(3L)
			.withChunkErrorCount(6L).withSkipInReadCount(0L).withSkipInProcessCount(2L).withSkipInWriteCount(0L)
			.build();
	validator.validate();
	// if one is correct, all will be in the metricReader, so I check just one
	Gauge gauge = meterRegistry.find(MetricsListener.METRIC_NAME)//
			.tag("context", "flatFileToDbSkipJob.step")//
			.tag("name", MetricNames.PROCESS_COUNT.getName())//
			.gauge();
	assertThat((Double) gauge.value(), is(notNullValue()));
	assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ITEM", Long.class), is(writeCount));
}
 
Example #3
Source File: MicrometerMessageGatewayMonitor.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
public MicrometerMessageGatewayMonitor(MeterRegistry registry, String id, String[] tags) {
    this.registry = registry;
    this.id = id;
    this.tags = tags;
    Gauge
        .builder(id, totalRef, AtomicReference::get)
        .tags(tags)
        .tag("target", "sessionNumber")
        .register(registry);

    this.acceptedSession = getCounter("accepted_session");
    this.closedSession = getCounter("closed_session");
    this.subscribed = getCounter("subscribed");
    this.unsubscribed = getCounter("unsubscribed");
    this.acceptMessage = getCounter("accept_message");

}
 
Example #4
Source File: HazelCastInstanceMetrics.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {

    Tags tags =
        Tags.of("name", name, "h_address", hazelcastInstance.getCluster().getLocalMember().getAddress().getHost())
            .and(platformTag.getTags());
    Gauge
        .builder("hazelcast.cluster.state", hazelcastInstance,
            hazelcastInstance -> hazelcastInstance.getCluster().getClusterState().ordinal())
        .tags(tags).description("ClusterState of HazelCast ").register(registry);
    Gauge
        .builder("hazelcast.client.connected.count", hazelcastInstance,
            hazelcastInstance -> hazelcastInstance.getClientService().getConnectedClients().size())
        .tags(tags).description("all connected clients to this member ").register(registry);
    Gauge
        .builder("hazelcast.partition.count", hazelcastInstance,
            hazelcastInstance -> hazelcastInstance.getPartitionService().getPartitions().size())
        .tags(tags).description("all partitions in the cluster").register(registry);
}
 
Example #5
Source File: KafkaBinderMetrics.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
	for (Map.Entry<String, KafkaMessageChannelBinder.TopicInformation> topicInfo : this.binder
			.getTopicsInUse().entrySet()) {

		if (!topicInfo.getValue().isConsumerTopic()) {
			continue;
		}

		String topic = topicInfo.getKey();
		String group = topicInfo.getValue().getConsumerGroup();

		Gauge.builder(METRIC_NAME, this,
				(o) -> computeUnconsumedMessages(topic, group)).tag("group", group)
				.tag("topic", topic)
				.description("Unconsumed messages for a particular group and topic")
				.register(registry);
	}
}
 
Example #6
Source File: InfinispanCacheMeterBinder.java    From infinispan-spring-boot with Apache License 2.0 6 votes vote down vote up
private void memory(MeterRegistry registry) {
   Gauge.builder("cache.memory.size", cache, cache -> cache.getAdvancedCache().getStats().getCurrentNumberOfEntriesInMemory())
         .tags(getTagsWithCacheName())
         .description("Number of entries currently in the cache, excluding passivated entries")
         .register(registry);

   if (cache.getCacheConfiguration().memory().evictionStrategy().isEnabled()) {
      Gauge.builder("cache.memory.used", cache, cache -> cache.getAdvancedCache().getStats().getDataMemoryUsed())
            .tags(getTagsWithCacheName())
            .description("Provides how much memory the current eviction algorithm estimates is in use for data")
            .register(registry);
   }

   Gauge.builder("cache.memory.offHeap", cache, cache -> cache.getAdvancedCache().getStats().getOffHeapMemoryUsed())
         .tags(getTagsWithCacheName())
         .description("The amount of off-heap memory used by this cache")
         .register(registry);
}
 
Example #7
Source File: ClusterCheckerTask.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param genieHostInfo         Information about the host this Genie process is running on
 * @param properties            The properties to use to configure the task
 * @param dataServices          The {@link DataServices} encapsulation instance to use
 * @param restTemplate          The rest template for http calls
 * @param webEndpointProperties The properties where Spring actuator is running
 * @param registry              The spectator registry for getting metrics
 */
public ClusterCheckerTask(
    @NotNull final GenieHostInfo genieHostInfo,
    @NotNull final ClusterCheckerProperties properties,
    @NotNull final DataServices dataServices,
    @NotNull final RestTemplate restTemplate,
    @NotNull final WebEndpointProperties webEndpointProperties,
    @NotNull final MeterRegistry registry
) {
    this.hostname = genieHostInfo.getHostname();
    this.properties = properties;
    this.persistenceService = dataServices.getPersistenceService();
    this.restTemplate = restTemplate;
    this.registry = registry;
    this.scheme = this.properties.getScheme() + "://";
    this.healthEndpoint = ":" + this.properties.getPort() + webEndpointProperties.getBasePath() + "/health";
    this.healthIndicatorsToIgnore = Splitter.on(",").omitEmptyStrings()
        .trimResults().splitToList(properties.getHealthIndicatorsToIgnore());
    // Keep track of the number of nodes currently unreachable from the the master
    Gauge.builder(UNHEALTHY_HOSTS_GAUGE_METRIC_NAME, this.errorCounts, Map::size)
        .register(registry);
}
 
Example #8
Source File: BatchMetricsFlatFileToDbIntegrationTest.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunFlatFileToDbSkipJob_SkipInProcess() throws InterruptedException {
	JobExecution jobExecution = runJob("flatFileToDbSkipJob", "metrics/flatFileToDbSkipJob_SkipInProcess.csv");
	assertThat(jobExecution.getStatus(), is(BatchStatus.COMPLETED));
	ExecutionContext executionContext = jobExecution.getStepExecutions().iterator().next().getExecutionContext();
	long writeCount = 7L;
	MetricValidator validator = MetricValidatorBuilder.metricValidator().withExecutionContext(executionContext)
			.withBeforeChunkCount(3L).withStreamOpenCount(1L).withStreamUpdateCount(4L).withStreamCloseCount(0L)
			.withBeforeReadCount(9L).withReadCount(9L).withAfterReadCount(8L).withReadErrorCount(0L)
			.withBeforeProcessCount(7L).withProcessCount(7L).withAfterProcessCount(7L).withProcessErrorCount(1L)
			.withBeforeWriteCount(7L).withWriteCount(writeCount).withAfterWriteCount(7L).withAfterChunkCount(3L)
			.withChunkErrorCount(1L).withSkipInReadCount(0L).withSkipInProcessCount(1L).withSkipInWriteCount(0L)
			.build();
	validator.validate();
	// if one is correct, all will be in the metricReader, so I check just one
	Gauge gauge = meterRegistry.find(MetricsListener.METRIC_NAME)//
			.tag("context", "flatFileToDbSkipJob.step")//
			.tag("name", MetricNames.PROCESS_COUNT.getName())//
			.gauge();
	assertThat((Double) gauge.value(), is(notNullValue()));
	assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ITEM", Long.class), is(writeCount));
}
 
Example #9
Source File: HealthStatsDefault.java    From pepper-metrics with Apache License 2.0 6 votes vote down vote up
private AtomicDouble getOrInitGauge(String gaugeName, Tags tagsFuc) {
    final AtomicDouble gauge = gaugeCollector.get(gaugeName);
    if (gauge != null) return gauge;
    synchronized (gaugeCollector) {
        if (gaugeCollector.get(gaugeName) == null) {
            final AtomicDouble obj = new AtomicDouble();
            String metricsName = MetricsNameBuilder.builder()
                    .setMetricsType(MetricsType.GAUGE)
                    .setType(getType())
                    .setSubType(getSubType())
                    .setName(gaugeName)
                    .build();
            Gauge.builder(metricsName, obj, AtomicDouble::get).tags(tagsFuc.tags()).register(getRegistry());
            gaugeCollector.putIfAbsent(gaugeName, obj);
        }
    }
    return gaugeCollector.get(gaugeName);
}
 
Example #10
Source File: BatchMetricsFlatFileToDbIntegrationTest.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunFlatFileToDbNoSkipJob_Success() throws InterruptedException {
	JobExecution jobExecution = runJob("flatFileToDbNoSkipJob", "metrics/flatFileToDbNoSkipJob_Success.csv");
	assertThat(jobExecution.getStatus(), is(BatchStatus.COMPLETED));
	ExecutionContext executionContext = jobExecution.getStepExecutions().iterator().next().getExecutionContext();
	long writeCount = 5L;
	MetricValidator validator = MetricValidatorBuilder.metricValidator().withExecutionContext(executionContext)
			.withBeforeChunkCount(2L).withStreamOpenCount(1L).withStreamUpdateCount(3L).withStreamCloseCount(0L)
			.withBeforeReadCount(6L).withReadCount(6L).withAfterReadCount(5L).withReadErrorCount(0L)
			.withBeforeProcessCount(5L).withProcessCount(5L).withAfterProcessCount(5L).withProcessErrorCount(0L)
			.withBeforeWriteCount(5L).withWriteCount(writeCount).withAfterWriteCount(5L).withAfterChunkCount(2L)
			.withChunkErrorCount(0L).withSkipInReadCount(0L).withSkipInProcessCount(0L).withSkipInWriteCount(0L)
			.build();
	validator.validate();
	// if one is correct, all will be in the metricReader, so I check just one
	Gauge gauge = meterRegistry.find(MetricsListener.METRIC_NAME)//
			.tag("context", "flatFileToDbNoSkipJob.step")//
			.tag("name", MetricNames.PROCESS_COUNT.getName())//
			.gauge();
	assertThat((Double) gauge.value(), is(notNullValue())); // TODO
	assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ITEM", Long.class), is(writeCount));
}
 
Example #11
Source File: KafkaConsumerMetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void verifyConsumerMetricsWithExpectedTags() {
    try (Consumer<Long, String> consumer = createConsumer()) {

        MeterRegistry registry = new SimpleMeterRegistry();
        kafkaConsumerMetrics.bindTo(registry);

        // consumer coordinator metrics
        Gauge assignedPartitions = registry.get("kafka.consumer.assigned.partitions").tags(tags).gauge();
        assertThat(assignedPartitions.getId().getTag("client.id")).isEqualTo("consumer-" + consumerCount);

        // global connection metrics
        Gauge connectionCount = registry.get("kafka.consumer.connection.count").tags(tags).gauge();
        assertThat(connectionCount.getId().getTag("client.id")).startsWith("consumer-" + consumerCount);
    }
}
 
Example #12
Source File: TaggedBulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<Gauge> gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, bulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls());

    Bulkhead newBulkhead = Bulkhead.of(bulkhead.getName(), BulkheadConfig.custom()
        .maxConcurrentCalls(100).build());

    bulkheadRegistry.replace(bulkhead.getName(), newBulkhead);

    gauges = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME)
        .gauges();

    successful = findMeterByNamesTag(gauges, newBulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());

}
 
Example #13
Source File: Ball.java    From demo-mesh-arena with Apache License 2.0 6 votes vote down vote up
private Ball(Vertx vertx) {
  client = WebClient.create(vertx);
  id = "ball-" + UUID.randomUUID().toString();
  json = new JsonObject()
      .put("id", id)
      .put("style", "position: absolute; background-image: url(./" + IMAGE + ".png); width: 20px; height: 20px;"
          + "z-index: 5; transition: top " + DELTA_MS + "ms, left " + DELTA_MS + "ms;")
      .put("text", "");

  registry = Optional.ofNullable(BackendRegistries.getDefaultNow());
  registry.ifPresent(reg -> Gauge.builder("mesharena_ball_speed", () -> speed.size())
      .description("Ball speed gauge")
      .register(reg));
  if (!registry.isPresent()) {
    System.out.println("No metrics");
  }
}
 
Example #14
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimer_whenEnrichWithQuantile_thenQuantilesComputed() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    Timer timer = Timer
      .builder("test.timer")
      .quantiles(WindowSketchQuantiles
        .quantiles(0.3, 0.5, 0.95)
        .create())
      .register(registry);

    timer.record(2, TimeUnit.SECONDS);
    timer.record(2, TimeUnit.SECONDS);
    timer.record(3, TimeUnit.SECONDS);
    timer.record(4, TimeUnit.SECONDS);
    timer.record(8, TimeUnit.SECONDS);
    timer.record(13, TimeUnit.SECONDS);

    Map<String, Integer> quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9);
    assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8)));
}
 
Example #15
Source File: PooledConnectionProviderMetrics.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void registerMetrics(String poolName, String id, String remoteAddress,
		InstrumentedPool.PoolMetrics metrics) {
	String[] tags = new String[] {ID, id, REMOTE_ADDRESS, remoteAddress, NAME, poolName};
	Gauge.builder(CONNECTION_PROVIDER_PREFIX + TOTAL_CONNECTIONS, metrics, InstrumentedPool.PoolMetrics::allocatedSize)
	     .description("The number of all connections, active or idle.")
	     .tags(tags)
	     .register(REGISTRY);

	Gauge.builder(CONNECTION_PROVIDER_PREFIX + ACTIVE_CONNECTIONS, metrics, InstrumentedPool.PoolMetrics::acquiredSize)
	     .description("The number of the connections that have been successfully acquired and are in active use")
	     .tags(tags)
	     .register(REGISTRY);

	Gauge.builder(CONNECTION_PROVIDER_PREFIX + IDLE_CONNECTIONS, metrics, InstrumentedPool.PoolMetrics::idleSize)
	     .description("The number of the idle connections")
	     .tags(tags)
	     .register(REGISTRY);

	Gauge.builder(CONNECTION_PROVIDER_PREFIX + PENDING_CONNECTIONS, metrics, InstrumentedPool.PoolMetrics::pendingAcquireSize)
	     .description("The number of the request, that are pending acquire a connection")
	     .tags(tags)
	     .register(REGISTRY);
}
 
Example #16
Source File: TaggedRateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRateLimiter() {
    RateLimiter newRateLimiter = rateLimiterRegistry.rateLimiter("backendB");

    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap)
        .containsKeys("backendA", "backendB");
    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap.get("backendA")).hasSize(2);
    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap.get("backendB")).hasSize(2);

    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(4);

    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME)
        .gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, newRateLimiter.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newRateLimiter.getMetrics().getAvailablePermissions());
}
 
Example #17
Source File: LdapSearchMetrics.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
public LdapSearchMetrics(MeterRegistry meterRegistry) {
    Gauge.builder("totalCallsCounter", this,
            LdapSearchMetrics::getTotalCallsCounterAndReset)
            .tags("class", this.getClass().getSimpleName())
            .register(meterRegistry);
    Gauge.builder("failedCallsCounter", this,
            LdapSearchMetrics::getFailedCallsCounterAndReset)
            .tags("class", this.getClass().getSimpleName())
            .register(meterRegistry);
    Gauge.builder("unexpectedExceptionCounter", this,
            LdapSearchMetrics::getUnexpectedExceptionCounterAndReset)
            .tags("class", this.getClass().getSimpleName())
            .register(meterRegistry);
    Gauge.builder("retriesExhaustedExceptionCounter", this,
            LdapSearchMetrics::getRetriesExhaustedExceptionCounterAndReset)
            .tags("class", this.getClass().getSimpleName())
            .register(meterRegistry);
}
 
Example #18
Source File: TaggedBulkheadMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRetry() {
    Bulkhead newBulkhead = bulkheadRegistry.bulkhead("backendB");

    assertThat(taggedBulkheadMetrics.meterIdMap).containsKeys("backendA", "backendB");
    assertThat(taggedBulkheadMetrics.meterIdMap.get("backendA")).hasSize(2);
    assertThat(taggedBulkheadMetrics.meterIdMap.get("backendB")).hasSize(2);

    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(4);

    Collection<Gauge> gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, newBulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());
}
 
Example #19
Source File: FileDescriptorMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    if (openFilesMethod != null) {
        Gauge.builder("process.files.open", osBean, x -> invoke(openFilesMethod))
                .tags(tags)
                .description("The open file descriptor count")
                .baseUnit(BaseUnits.FILES)
                .register(registry);
    }

    if (maxFilesMethod != null) {
        Gauge.builder("process.files.max", osBean, x -> invoke(maxFilesMethod))
                .tags(tags)
                .description("The maximum file descriptor count")
                .baseUnit(BaseUnits.FILES)
                .register(registry);
    }
}
 
Example #20
Source File: MetricsManager.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void registerAddressGauge(String address, Consumer<MetricGaugeBuilder> builder) {
   final MeterRegistry meterRegistry = this.meterRegistry;
   if (meterRegistry == null || !addressSettingsRepository.getMatch(address).isEnableMetrics()) {
      return;
   }
   final List<Gauge.Builder> newMeters = new ArrayList<>();
   builder.accept((metricName, state, f, description) -> {
      Gauge.Builder meter = Gauge
         .builder("artemis." + metricName, state, f)
         .tag("broker", brokerName)
         .tag("address", address)
         .description(description);
      newMeters.add(meter);
   });
   final String resource = ResourceNames.ADDRESS + address;
   this.meters.compute(resource, (s, meters) -> {
      //the old meters are ignored on purpose
      meters = new ArrayList<>(newMeters.size());
      for (Gauge.Builder gauge : newMeters) {
         meters.add(gauge.register(meterRegistry));
      }
      return meters;
   });
}
 
Example #21
Source File: TaggedRateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Gauge availablePermissions = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME)
        .gauge();

    assertThat(availablePermissions).isNotNull();
    assertThat(availablePermissions.value())
        .isEqualTo(rateLimiter.getMetrics().getAvailablePermissions());
    assertThat(availablePermissions.getId().getTag(TagNames.NAME))
        .isEqualTo(rateLimiter.getName());

    RateLimiter newRateLimiter = RateLimiter
        .of(rateLimiter.getName(), RateLimiterConfig.custom().limitForPeriod(1000).build());

    rateLimiterRegistry.replace(rateLimiter.getName(), newRateLimiter);

    availablePermissions = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME).gauge();

    assertThat(availablePermissions).isNotNull();
    assertThat(availablePermissions.value())
        .isEqualTo(newRateLimiter.getMetrics().getAvailablePermissions());
    assertThat(availablePermissions.getId().getTag(TagNames.NAME))
        .isEqualTo(newRateLimiter.getName());
}
 
Example #22
Source File: BatchMetricsFlatFileToDbIntegrationTest.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunFlatFileToDbSkipJob_SkipInRead() throws InterruptedException {
	JobExecution jobExecution = runJob("flatFileToDbSkipJob", "metrics/flatFileToDbSkipJob_SkipInRead.csv");
	assertThat(jobExecution.getStatus(), is(BatchStatus.COMPLETED));
	ExecutionContext executionContext = jobExecution.getStepExecutions().iterator().next().getExecutionContext();
	long writeCount = 7L;
	MetricValidator validator = MetricValidatorBuilder.metricValidator().withExecutionContext(executionContext)
			.withBeforeChunkCount(3L).withStreamOpenCount(1L).withStreamUpdateCount(4L).withStreamCloseCount(0L)
			.withBeforeReadCount(9L).withReadCount(9L).withAfterReadCount(7L).withReadErrorCount(1L)
			.withBeforeProcessCount(7L).withProcessCount(7L).withAfterProcessCount(7L).withProcessErrorCount(0L)
			.withBeforeWriteCount(7L).withWriteCount(writeCount).withAfterWriteCount(7L).withWriteErrorCount(0L)
			.withAfterChunkCount(3L).withChunkErrorCount(0L).withSkipInReadCount(1L).withSkipInProcessCount(0L)
			.withSkipInWriteCount(0L).build();
	validator.validate();
	// if one is correct, all will be in the metricReader, so I check just one
	Gauge gauge = meterRegistry.find(MetricsListener.METRIC_NAME)//
			.tag("context", "flatFileToDbSkipJob.step")//
			.tag("name", MetricNames.PROCESS_COUNT.getName())//
			.gauge();
	assertThat((Double) gauge.value(), is(notNullValue()));
	assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ITEM", Long.class), is(writeCount));
}
 
Example #23
Source File: GaugesTest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreGaugeLabel() {
  MeterRegistry registry = new SimpleMeterRegistry();
  BackendRegistries.registerMatchers(registry, ALL_LABELS, Collections.singletonList(new Match()
    .setLabel("address")
    .setType(MatchType.REGEX)
    .setValue(".*")
    .setAlias("_")));
  Gauges<LongAdder> gauges = new Gauges<>("my_gauge", "", LongAdder::new, LongAdder::doubleValue, registry, Label.EB_ADDRESS);
  gauges.get("addr1").increment();
  gauges.get("addr1").increment();
  gauges.get("addr2").increment();

  Gauge g = registry.find("my_gauge").tags("address", "_").gauge();
  assertThat(g.value()).isEqualTo(3d);
  g = registry.find("my_gauge").tags("address", "addr1").gauge();
  assertThat(g).isNull();
  g = registry.find("my_gauge").tags("address", "addr2").gauge();
  assertThat(g).isNull();
}
 
Example #24
Source File: TaggedCircuitBreakerMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedCircuitBreaker() {
    CircuitBreaker newCircuitBreaker = circuitBreakerRegistry.circuitBreaker("backendB");
    newCircuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);

    assertThat(taggedCircuitBreakerMetrics.meterIdMap).containsKeys("backendA", "backendB");
    assertThat(taggedCircuitBreakerMetrics.meterIdMap.get("backendA")).hasSize(16);
    assertThat(taggedCircuitBreakerMetrics.meterIdMap.get("backendB")).hasSize(16);

    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(32);

    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS)
        .gauges();

    Optional<Gauge> successful = MetricsTestHelper
        .findMeterByKindAndNameTags(gauges, "successful",
        newCircuitBreaker.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newCircuitBreaker.getMetrics().getNumberOfSuccessfulCalls());
}
 
Example #25
Source File: MicrometerReporterMetrics.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
private MicrometerReporterMetrics(MeterRegistry meterRegistry, Tag... extraTags) {
  this.meterRegistry = meterRegistry;
  this.extraTags = Arrays.asList(extraTags);

  messages = Counter.builder(PREFIX + "messages.total")
    .description("Messages reported (or attempted to be reported)")
    .tags(this.extraTags).register(meterRegistry);
  messageBytes = Counter.builder(PREFIX + "messages")
    .description("Total bytes of messages reported")
    .baseUnit("bytes")
    .tags(this.extraTags).register(meterRegistry);
  spans = Counter.builder(PREFIX + "spans.total")
    .description("Spans reported")
    .tags(this.extraTags).register(meterRegistry);
  spanBytes = Counter.builder(PREFIX + "spans")
    .description("Total bytes of encoded spans reported")
    .baseUnit("bytes")
    .tags(this.extraTags).register(meterRegistry);
  spansDropped = Counter.builder(PREFIX + "spans.dropped")
    .description("Spans dropped (failed to report)")
    .tags(this.extraTags).register(meterRegistry);
  queuedSpans = new AtomicInteger();
  Gauge.builder(PREFIX + "queue.spans", queuedSpans, AtomicInteger::get)
    .description("Spans queued for reporting")
    .tags(this.extraTags).register(meterRegistry);
  queuedBytes = new AtomicInteger();
  Gauge.builder(PREFIX + "queue.bytes", queuedBytes, AtomicInteger::get)
    .description("Total size of all encoded spans queued for reporting")
    .baseUnit("bytes")
    .tags(this.extraTags).register(meterRegistry);
}
 
Example #26
Source File: TaggedCircuitBreakerMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void stateGaugeReportsCorrespondingValue() {
    Gauge state = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_STATE).gauge();

    assertThat(state.value()).isEqualTo(circuitBreaker.getState().getOrder());
    assertThat(state.getId().getTag(TagNames.NAME)).isEqualTo(circuitBreaker.getName());
}
 
Example #27
Source File: TaggedCircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void failedCallsGaugeReportsCorrespondingValue() {
    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS)
        .gauges();

    Optional<Gauge> failed = MetricsTestHelper.findMeterByKindAndNameTags(gauges, "failed",
        circuitBreaker.getName());
    assertThat(failed).isPresent();
    assertThat(failed.get().value())
        .isEqualTo(circuitBreaker.getMetrics().getNumberOfFailedCalls());
}
 
Example #28
Source File: MongoMetricsConnectionPoolListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private Gauge registerGauge(ServerId serverId, String metricName, String description, Map<ServerId, AtomicInteger> metrics) {
    AtomicInteger value = new AtomicInteger();
    metrics.put(serverId, value);
    return Gauge.builder(metricName, value, AtomicInteger::doubleValue)
                .description(description)
                .tag("cluster.id", serverId.getClusterId().getValue())
                .tag("server.address", serverId.getAddress().toString())
                .register(registry);
}
 
Example #29
Source File: StatsdGaugeTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void shouldAlwaysPublishValue() {
    AtomicInteger lines = new AtomicInteger(0);
    MeterRegistry registry = StatsdMeterRegistry.builder(StatsdConfig.DEFAULT)
            .lineSink(l -> lines.incrementAndGet())
            .build();

    StatsdGauge<?> alwaysPublishingGauge = (StatsdGauge<?>) Gauge
            .builder("test", value, AtomicInteger::get).register(registry);

    alwaysPublishingGauge.poll();
    alwaysPublishingGauge.poll();

    assertThat(lines.get()).isEqualTo(2);
}
 
Example #30
Source File: TaggedCircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void slowFailedCallsGaugeReportsCorrespondingValue() {
    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_SLOW_CALLS).gauges();

    Optional<Gauge> slow = MetricsTestHelper.findMeterByKindAndNameTags(gauges, "failed",
        circuitBreaker.getName());
    assertThat(slow).isPresent();
    assertThat(slow.get().value())
        .isEqualTo(circuitBreaker.getMetrics().getNumberOfSlowFailedCalls());
}