io.micrometer.core.instrument.FunctionCounter Java Examples

The following examples show how to use io.micrometer.core.instrument.FunctionCounter. 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: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();
    Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
        "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());

    Retry newRetry = Retry.of(retry.getName(), RetryConfig.custom().maxAttempts(1).build());

    retryRegistry.replace(retry.getName(), newRetry);

    counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    successfulWithoutRetry = findMeterByKindAndNameTags(counters, "successful_without_retry",
        newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #3
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRetry() {
    Retry newRetry = retryRegistry.retry("backendB");

    assertThat(taggedRetryMetrics.meterIdMap).containsKeys("backendA", "backendB");
    assertThat(taggedRetryMetrics.meterIdMap.get("backendA")).hasSize(4);
    assertThat(taggedRetryMetrics.meterIdMap.get("backendB")).hasSize(4);

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

    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
        "successful_without_retry", newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #4
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    Optional<FunctionCounter> successfulWithoutRetry = MetricsTestHelper.findMeterByKindAndNameTags(counters,
        "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());

    Retry newRetry = Retry.of(retry.getName(), RetryConfig.custom().maxAttempts(1).build());

    retryRegistry.replace(retry.getName(), newRetry);

    counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    successfulWithoutRetry = MetricsTestHelper
        .findMeterByKindAndNameTags(counters, "successful_without_retry",
        newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #5
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRetry() {
    Retry newRetry = retryRegistry.retry("backendB");

    assertThat(taggedRetryMetricsPublisher.meterIdMap).containsKeys("backendA", "backendB");
    assertThat(taggedRetryMetricsPublisher.meterIdMap.get("backendA")).hasSize(4);
    assertThat(taggedRetryMetricsPublisher.meterIdMap.get("backendB")).hasSize(4);

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

    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithoutRetry = MetricsTestHelper
        .findMeterByKindAndNameTags(counters, "successful_without_retry", newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #6
Source File: SchedulersMetricsTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters(method = "metricsSchedulers")
   public void shouldReportExecutorMetrics(Supplier<Scheduler> schedulerSupplier, String type) {
	Scheduler scheduler = afterTest.autoDispose(schedulerSupplier.get());
	final int taskCount = 3;

	for (int i = 0; i < taskCount; i++) {
		scheduler.schedule(() -> {
		});
	}

	Collection<FunctionCounter> counters = simpleMeterRegistry
			.find("executor.completed")
			.tag(TAG_SCHEDULER_ID, scheduler.toString())
			.functionCounters();

	// Use Awaitility because "count" is reported "eventually"
	await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
		assertThat(counters.stream()
		                   .mapToDouble(FunctionCounter::count)
		                   .sum())
				.isEqualTo(taskCount);
	});
   }
 
Example #7
Source File: CaffeineCacheMetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void reportExpectedGeneralMetrics() {
    MeterRegistry registry = new SimpleMeterRegistry();
    metrics.bindTo(registry);

    verifyCommonCacheMetrics(registry, metrics);

    FunctionCounter evictionWeight = fetch(registry, "cache.eviction.weight").functionCounter();
    CacheStats stats = cache.stats();
    assertThat(evictionWeight.count()).isEqualTo(stats.evictionWeight());

    // specific to LoadingCache instance
    TimeGauge loadDuration = fetch(registry, "cache.load.duration").timeGauge();
    assertThat(loadDuration.value()).isEqualTo(stats.totalLoadTime());

    FunctionCounter successfulLoad = fetch(registry, "cache.load", Tags.of("result", "success")).functionCounter();
    assertThat(successfulLoad.count()).isEqualTo(stats.loadSuccessCount());

    FunctionCounter failedLoad = fetch(registry, "cache.load", Tags.of("result", "failure")).functionCounter();
    assertThat(failedLoad.count()).isEqualTo(stats.loadFailureCount());
}
 
Example #8
Source File: FunctionCounterSample.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();

    AtomicInteger n = new AtomicInteger(0);

    FunctionCounter.builder("my.fcounter", n, AtomicInteger::get)
        .baseUnit("happiness")
        .description("A counter derived from a monotonically increasing value")
        .register(registry);

    Counter counter = Counter.builder("my.counter")
        .baseUnit("happiness")
        .description("A normal counter")
        .register(registry);

    Flux.interval(Duration.ofMillis(10))
        .doOnEach(i -> {
            n.incrementAndGet();
            counter.increment();
        })
        .blockLast();
}
 
Example #9
Source File: MemcachedCacheMeterBinderProviderConfigurationTest.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void whenMemcachedCacheManagerBeanThenCacheStatisticsLoaded() {
    loadContext(CacheWithMemcachedCacheManagerConfiguration.class);

    CacheMeterBinderProvider provider = this.context.getBean(
            "memcachedCacheMeterBinderProvider", CacheMeterBinderProvider.class);

    assertThat(provider).isNotNull();

    CacheManager cacheManager = this.context.getBean(CacheManager.class);
    Cache books = cacheManager.getCache("books");

    MeterBinder metrics = provider.getMeterBinder(books, expectedTag);

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

    FunctionCounter hits = registry.get("cache.gets").tags(expectedTag).tag("result", "hit").functionCounter();
    FunctionCounter misses = registry.get("cache.gets").tags(expectedTag).tag("result", "miss").functionCounter();
    FunctionCounter puts = registry.get("cache.puts").tags(expectedTag).functionCounter();
    double availableServersCount = registry.get("available_servers_count").gauge().value();

    assertThat(hits.count()).isEqualTo(0);
    assertThat(misses.count()).isEqualTo(0);
    assertThat(puts.count()).isEqualTo(0);
    assertThat(availableServersCount).isEqualTo(1.0);

    getCacheKeyValues(books, "a", "b", "b", "c", "d", "c", "a", "a", "a", "d");

    assertThat(hits.count()).isEqualTo(6);
    assertThat(misses.count()).isEqualTo(4);
    assertThat(puts.count()).isEqualTo(0);
    assertThat(availableServersCount).isEqualTo(1.0);
}
 
Example #10
Source File: AppOpticsMeterRegistryTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void writeFunctionCounterShouldDropInfiniteValues() {
    FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue).register(meterRegistry);
    clock.add(config.step());
    assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse();

    counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue).register(meterRegistry);
    clock.add(config.step());
    assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse();
}
 
Example #11
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceNewMeter() {
    Retry oldOne = Retry.of("backendC", RetryConfig.ofDefaults());
    // add meters of old
    taggedRetryMetricsPublisher.addMetrics(meterRegistry, oldOne);
    // one success call
    oldOne.executeRunnable(() -> { });

    assertThat(taggedRetryMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedRetryMetricsPublisher.meterIdMap.get("backendC")).hasSize(4);
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();
    Optional<FunctionCounter> successfulWithoutRetry =
        findMeterByKindAndNameTags(counters, "successful_without_retry", oldOne.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(oldOne.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());


    Retry newOne = Retry.of("backendC", RetryConfig.ofDefaults());
    // add meters of old
    taggedRetryMetricsPublisher.addMetrics(meterRegistry, newOne);
    // three success call
    newOne.executeRunnable(() -> { });
    newOne.executeRunnable(() -> { });
    newOne.executeRunnable(() -> { });

    assertThat(taggedRetryMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedRetryMetricsPublisher.meterIdMap.get("backendC")).hasSize(4);
    counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();
    successfulWithoutRetry =
        findMeterByKindAndNameTags(counters, "successful_without_retry", newOne.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newOne.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #12
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void failedWithRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS).
        functionCounters();

    Optional<FunctionCounter> failedWithRetry = MetricsTestHelper
        .findMeterByKindAndNameTags(counters, "failed_with_retry",
        retry.getName());
    assertThat(failedWithRetry).isPresent();
    assertThat(failedWithRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfFailedCallsWithRetryAttempt());
}
 
Example #13
Source File: KairosMeterRegistryTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void writeFunctionCounterShouldDropInfiniteValues() {
    FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue).register(meterRegistry);
    clock.add(config.step());
    assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty();

    counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue).register(meterRegistry);
    clock.add(config.step());
    assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty();
}
 
Example #14
Source File: MemcachedCacheIT.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void whenGettingBooksFromCacheThenReturnCorrectStatistics() {
    bookService.findAll();
    bookService.findAll();
    bookService.findAll();

    bookService.findByTitle("Spring Boot in Action");
    bookService.findByTitle("Spring Boot in Action");
    bookService.findByTitle("Kotlin");
    bookService.findByTitle("Kotlin");
    bookService.findByTitle("Kotlin");

    Cache books = cacheManager.getCache("books");

    Tags expectedTag = Tags.of("app", "test");
    MeterBinder metrics = provider.getMeterBinder(books, expectedTag);

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

    FunctionCounter hits = registry.get("cache.gets").tags(expectedTag).tag("result", "hit").functionCounter();
    FunctionCounter misses = registry.get("cache.gets").tags(expectedTag).tag("result", "miss").functionCounter();

    assertThat(hits.count()).isEqualTo(5);
    assertThat(misses.count()).isEqualTo(3);

    bookService.findAll();
    bookService.findByTitle("Kotlin");

    assertThat(hits.count()).isEqualTo(7);
    assertThat(misses.count()).isEqualTo(3);
}
 
Example #15
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulWithRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithRetry = findMeterByKindAndNameTags(counters,
        "successful_with_retry", retry.getName());
    assertThat(successfulWithRetry).isPresent();
    assertThat(successfulWithRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt());
}
 
Example #16
Source File: AbstractRetryMetrics.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private void registerMetrics(MeterRegistry meterRegistry, Retry retry, List<Tag> customTags) {
    // Remove previous meters before register
    removeMetrics(meterRegistry, retry.getName());

    Set<Meter.Id> idSet = new HashSet<>();
    idSet.add(FunctionCounter.builder(names.getCallsMetricName(), retry,
        rt -> rt.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt())
        .description("The number of successful calls without a retry attempt")
        .tag(TagNames.NAME, retry.getName())
        .tag(TagNames.KIND, "successful_without_retry")
        .tags(customTags)
        .register(meterRegistry).getId());
    idSet.add(FunctionCounter.builder(names.getCallsMetricName(), retry,
        rt -> rt.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt())
        .description("The number of successful calls after a retry attempt")
        .tag(TagNames.NAME, retry.getName())
        .tag(TagNames.KIND, "successful_with_retry")
        .tags(customTags)
        .register(meterRegistry).getId());
    idSet.add(FunctionCounter.builder(names.getCallsMetricName(), retry,
        rt -> rt.getMetrics().getNumberOfFailedCallsWithoutRetryAttempt())
        .description("The number of failed calls without a retry attempt")
        .tag(TagNames.NAME, retry.getName())
        .tag(TagNames.KIND, "failed_without_retry")
        .tags(customTags)
        .register(meterRegistry).getId());
    idSet.add(FunctionCounter.builder(names.getCallsMetricName(), retry,
        rt -> rt.getMetrics().getNumberOfFailedCallsWithRetryAttempt())
        .description("The number of failed calls after a retry attempt")
        .tag(TagNames.NAME, retry.getName())
        .tag(TagNames.KIND, "failed_with_retry")
        .tags(customTags)
        .register(meterRegistry).getId());
    meterIdMap.put(retry.getName(), idSet);
}
 
Example #17
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulWithoutRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(
        counters, "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #18
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulWithRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithRetry = MetricsTestHelper.findMeterByKindAndNameTags(counters,
        "successful_with_retry", retry.getName());
    assertThat(successfulWithRetry).isPresent();
    assertThat(successfulWithRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt());
}
 
Example #19
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void failedWithoutRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> failedWithoutRetry = MetricsTestHelper.findMeterByKindAndNameTags(
        counters, "failed_without_retry", retry.getName());
    assertThat(failedWithoutRetry).isPresent();
    assertThat(failedWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfFailedCallsWithoutRetryAttempt());
}
 
Example #20
Source File: StepFunctionCounterTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void count() {
    AtomicInteger n = new AtomicInteger(1);
    FunctionCounter counter = registry.more().counter("my.counter", Tags.empty(), n);

    assertThat(counter).isInstanceOf(StepFunctionCounter.class);
    assertThat(counter.count()).isEqualTo(0);
    clock.add(config.step());
    assertThat(counter.count()).isEqualTo(1);
}
 
Example #21
Source File: ThreadPoolBinder.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void monitor(MeterRegistry registry, ThreadPoolExecutor tp) {
    FunctionCounter.builder(name + ".completed", tp, ThreadPoolExecutor::getCompletedTaskCount).tags(tags)
        .description("The approximate total number of tasks that have completed execution").register(registry);

    Gauge.builder(name + ".active", tp, ThreadPoolExecutor::getActiveCount).tags(tags)
        .description("The approximate number of threads that are actively executing tasks").register(registry);

    Gauge.builder(name + ".queued", tp, tpRef -> tpRef.getQueue().size()).tags(tags)
        .description("The approximate number of threads that are queued for execution").register(registry);

    Gauge.builder(name + ".pool", tp, ThreadPoolExecutor::getPoolSize).tags(tags)
        .description("The current number of threads in the pool").register(registry);
}
 
Example #22
Source File: ThreadPoolBinder.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void monitor(String name, ScheduledThreadPoolExecutor tp, MeterRegistry meterRegistry, Iterable<Tag> tags) {
    FunctionCounter.builder(name + ".completed", tp, ScheduledThreadPoolExecutor::getCompletedTaskCount).tags(tags)
        .description("The approximate total number of tasks that have completed execution").register(meterRegistry);
    Gauge.builder(name + ".active", tp, ScheduledThreadPoolExecutor::getActiveCount).tags(tags)
        .description("The approximate number of threads that are actively executing tasks").register(meterRegistry);
    Gauge.builder(name + ".queued", tp, (tpRef) -> {
        return (double)tpRef.getQueue().size();
    }).tags(tags).description("The approximate number of threads that are queued for execution")
        .register(meterRegistry);
    Gauge.builder(name + ".pool", tp, ScheduledThreadPoolExecutor::getPoolSize).tags(tags)
        .description("The current number of threads in the pool").register(meterRegistry);
}
 
Example #23
Source File: KafkaConsumerMetrics.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void registerFunctionCounterForObject(MeterRegistry registry, ObjectName o, String jmxMetricName,
    Tags allTags, String description, @Nullable String baseUnit) {
    FunctionCounter
        .builder(METRIC_NAME_PREFIX + sanitize(jmxMetricName), mBeanServer,
            s -> safeDouble(() -> s.getAttribute(o, jmxMetricName)))
        .description(description).baseUnit(baseUnit).tags(allTags).register(registry);
}
 
Example #24
Source File: JvmCompilationMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    CompilationMXBean compilationBean = ManagementFactory.getCompilationMXBean();
    if (compilationBean != null && compilationBean.isCompilationTimeMonitoringSupported()) {
        FunctionCounter.builder("jvm.compilation.time", compilationBean, CompilationMXBean::getTotalCompilationTime)
                .tags(Tags.concat(tags, "compiler", compilationBean.getName()))
                .description("The approximate accumulated elapsed time spent in compilation")
                .baseUnit(BaseUnits.MILLISECONDS)
                .register(registry);
    }
}
 
Example #25
Source File: KafkaMetricMeterTypeBuilder.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Build and register a typed meter.
 *
 * @return Optional type of {@link Meter}
 */
public Optional<Meter> build() {
    if (!isValid()) {
        return Optional.empty();
    }

    if (StringUtils.isEmpty(name)) {
        name = kafkaMetric.metricName().name();
    }

    KafkaMetricMeterType kafkaMetricMeterType = kafkaMetricMeterTypeRegistry.lookup(this.name);

    if (kafkaMetricMeterType.getMeterType() == MeterType.GAUGE && this.kafkaMetric.metricValue() instanceof Double) {
        return Optional.of(Gauge.builder(getMetricName(), () -> (Double) kafkaMetric.metricValue())
                .tags(tagFunction.apply(kafkaMetric.metricName()))
                .description(kafkaMetricMeterType.getDescription())
                .baseUnit(kafkaMetricMeterType.getBaseUnit())
                .register(meterRegistry));
    } else if (kafkaMetricMeterType.getMeterType() == MeterType.FUNCTION_COUNTER && this.kafkaMetric.metricValue() instanceof Double) {
        return Optional.of(FunctionCounter.builder(getMetricName(), kafkaMetric, value -> (Double) value.metricValue())
                .tags(tagFunction.apply(kafkaMetric.metricName()))
                .description(kafkaMetricMeterType.getDescription())
                .baseUnit(kafkaMetricMeterType.getBaseUnit())
                .register(meterRegistry));
    } else if (kafkaMetricMeterType.getMeterType() == MeterType.TIME_GAUGE && this.kafkaMetric.metricValue() instanceof Double) {
        return Optional.of(TimeGauge.builder(getMetricName(), kafkaMetric, kafkaMetricMeterType.getTimeUnit(), value -> (Double) value.metricValue())
                .tags(tagFunction.apply(kafkaMetric.metricName()))
                .description(kafkaMetricMeterType.getDescription())
                .register(meterRegistry));
    }

    return Optional.empty();
}
 
Example #26
Source File: SkywalkingMeterRegistry.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    final MeterId meterId = convertId(id);
    FunctionCounter fc = new CumulativeFunctionCounter<>(id, obj, countFunction);

    new SkywalkingCustomCounter.Builder(meterId, new Measurement(() -> countFunction.applyAsDouble(obj), Statistic.COUNT), config).build();
    return fc;
}
 
Example #27
Source File: CompositeFunctionCounter.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
FunctionCounter registerNewMeter(MeterRegistry registry) {
    final T obj = ref.get();
    if (obj == null) {
        return null;
    }

    return FunctionCounter.builder(getId().getName(), obj, f)
        .tags(getId().getTagsAsIterable())
        .description(getId().getDescription())
        .baseUnit(getId().getBaseUnit())
        .register(registry);
}
 
Example #28
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulWithoutRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
        "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #29
Source File: GuavaCacheMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void reportExpectedMetrics() {
    MeterRegistry registry = new SimpleMeterRegistry();
    metrics.bindTo(registry);

    verifyCommonCacheMetrics(registry, metrics);

    // common metrics
    Gauge cacheSize = fetch(registry, "cache.size").gauge();
    assertThat(cacheSize.value()).isEqualTo(cache.size());

    FunctionCounter hitCount = fetch(registry, "cache.gets", Tags.of("result", "hit")).functionCounter();
    assertThat(hitCount.count()).isEqualTo(metrics.hitCount());

    FunctionCounter missCount = fetch(registry, "cache.gets", Tags.of("result", "miss")).functionCounter();
    assertThat(missCount.count()).isEqualTo(metrics.missCount().doubleValue());

    FunctionCounter cachePuts = fetch(registry, "cache.puts").functionCounter();
    assertThat(cachePuts.count()).isEqualTo(metrics.putCount());

    FunctionCounter cacheEviction = fetch(registry, "cache.evictions").functionCounter();
    assertThat(cacheEviction.count()).isEqualTo(metrics.evictionCount().doubleValue());

    CacheStats stats = cache.stats();
    TimeGauge loadDuration = fetch(registry, "cache.load.duration").timeGauge();
    assertThat(loadDuration.value()).isEqualTo(stats.totalLoadTime());

    FunctionCounter successfulLoad = fetch(registry, "cache.load", Tags.of("result", "success")).functionCounter();
    assertThat(successfulLoad.count()).isEqualTo(stats.loadSuccessCount());

    FunctionCounter failedLoad = fetch(registry, "cache.load", Tags.of("result", "failure")).functionCounter();
    assertThat(failedLoad.count()).isEqualTo(stats.loadExceptionCount());
}
 
Example #30
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void failedWithRetryCallsGaugeReportsCorrespondingValue() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();

    Optional<FunctionCounter> failedWithRetry = findMeterByKindAndNameTags(counters,
        "failed_with_retry", retry.getName());
    assertThat(failedWithRetry).isPresent();
    assertThat(failedWithRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfFailedCallsWithRetryAttempt());
}