io.micrometer.core.instrument.Metrics Java Examples

The following examples show how to use io.micrometer.core.instrument.Metrics. 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: ProcessStreamService.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
private void createStreamInput(String inputTopic, String outputTopic) {
    StreamsBuilder builder = new StreamsBuilder();
    KStream<String, String> streamInput = builder.stream(inputTopic, Consumed.with(Serdes.String(), Serdes.String()));

    KStream<String, String> streamParsed = streamInput.mapValues((value) -> {
        Metrics.counter("skaetl_nb_read_kafka_count", Lists.newArrayList(Tag.of("processConsumerName", getProcessConsumer().getName()))).increment();
        return getGenericParser().apply(value, getProcessConsumer());
    }).filter((key, value) -> StringUtils.isNotBlank(value));

    final Serde<String> stringSerdes = Serdes.String();

    streamParsed.to(outputTopic, Produced.with(stringSerdes, stringSerdes));

    KafkaStreams streams = new KafkaStreams(builder.build(), KafkaUtils.createKStreamProperties(getProcessConsumer().getIdProcess() + ProcessConstants.INPUT_PROCESS, getBootstrapServer()));
    Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
    streams.start();
    addStreams(streams);
}
 
Example #2
Source File: TcpMetricsTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@After
public void tearDown() {
	if (disposableServer != null) {
		disposableServer.disposeNow();
	}

	if (connection != null) {
		connection.disposeNow();
	}

	provider.disposeLater()
	        .block(Duration.ofSeconds(30));

	Metrics.removeRegistry(registry);
	registry.clear();
	registry.close();
}
 
Example #3
Source File: UdpMetricsTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	udpServer =
			UdpServer.create()
			         .host("127.0.0.1")
			         .port(0)
			         .metrics(true);

	udpClient =
			UdpClient.create()
			         .remoteAddress(() -> serverConnection.address())
			         .metrics(true);

	registry = new SimpleMeterRegistry();
	Metrics.addRegistry(registry);
}
 
Example #4
Source File: BinderTests.java    From mewbase with MIT License 6 votes vote down vote up
private void metricsExpectations(Long expPuts, Long expGets, Long expDels, Long expDocs, String binderName) {

        final Counter puts = Metrics.globalRegistry.find("mewbase.binder.put")
                .tag("name", binderName)
                .counter();
        assertEquals(expPuts, puts.count(), 0.000001);

        final Counter gets = Metrics.globalRegistry.find("mewbase.binder.get")
                .tag("name", binderName)
                .counter();
        assertEquals(expGets, gets.count(), 0.000001);

        final Counter dels = Metrics.globalRegistry.find("mewbase.binder.delete")
                .tag("name", binderName)
                .counter();
        assertEquals(expDels, dels.count(),0.000001);

        final Gauge docs = Metrics.globalRegistry.find("mewbase.binder.documents")
                .tag("name", binderName)
                .gauge();
        assertEquals(expDocs, docs.value(), 0.000001);
    }
 
Example #5
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 #6
Source File: SchedulersMetricsTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void disablingMetricsRemovesSchedulerMeters() {
	afterTest.autoDispose(Schedulers.newParallel("A", 1));
	afterTest.autoDispose(Schedulers.newParallel("A", 1));
	afterTest.autoDispose(Schedulers.newParallel("A", 1));

	Metrics.globalRegistry.counter("foo", "tagged", "bar");

	Schedulers.disableMetrics();

	assertThat(simpleMeterRegistry.getMeters()
	                              .stream()
	                              .map(m -> m.getId().getName())
	                              .distinct())
			.containsExactly("foo");
}
 
Example #7
Source File: MeterMapCleanerTask.java    From summerframework with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry();
    Metrics.globalRegistry.add(meterRegistry);
    MeterMapCleanerTask task = new MeterMapCleanerTask(Metrics.globalRegistry);
    task.start("0/2 * * * * ?");

    ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
    s.scheduleAtFixedRate(() -> {
        meterRegistry.counter(UUID.randomUUID().toString()).increment();
        System.out.println(meterRegistry.getMeters().size());
    }, 0, 100, TimeUnit.MILLISECONDS);

    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    s.shutdown();
    task.stop();
}
 
Example #8
Source File: MicrometerMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCustomLabel() {
    String metricName = "testWithCustomLabel";

    // prepare
    SpanData spanData = defaultMockSpanData();
    MetricLabel metricLabel = new BaggageMetricLabel(METRIC_LABEL_NAME, METRIC_LABEL_VALUE);
    MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
            .withName(metricName)
            .withCustomLabel(metricLabel)
            .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT)
            .build();

    // test
    reporter.reportSpan(spanData);

    // verify
    List<Tag> tags = defaultTags();
    tags.add(new ImmutableTag(METRIC_LABEL_NAME, METRIC_LABEL_VALUE));

    assertEquals(100, (long) registry.find(metricName).timer().totalTime(TimeUnit.MILLISECONDS));
    assertEquals(1, Metrics.timer(metricName, tags).count());
}
 
Example #9
Source File: OpenfeignMetricsBinder.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Around("execution(* feign.Client.execute(..))")
public Response around(ProceedingJoinPoint pjp) throws Throwable {
    long start = MicrometerUtil.monotonicTime();
    Request request = (Request)pjp.getArgs()[0];
    Response response = null;
    Throwable e = null;
    try {
        response = (Response)pjp.proceed();
    } catch (Throwable t) {
        throw e = t;
    } finally {
        long lapsed = MicrometerUtil.monotonicTime() - start;
        Timer timer = Metrics.timer("openfeign",
            Tags.of(tags)
                .and(Tag.of("status", null == response ? "CLIENT_ERROR" : String.valueOf(response.status())),
                    Tag.of("method", request.method()), Tag.of("class", getKey(CLASS_HEADER, request.headers())),
                    Tag.of("classMethod", getKey(METHOD_HEADER, request.headers()))
                // Tag.of("url", getUrl(request.url()))
                ).and(MicrometerUtil.exceptionAndStatusKey(e)));
        timer.record(lapsed, TimeUnit.NANOSECONDS);
    }
    return response;
}
 
Example #10
Source File: MetricJdbcEventListener.java    From summerframework with Apache License 2.0 6 votes vote down vote up
protected void record(Loggable loggable, long timeElapsedNanos, Category category, SQLException e) {
    try {
        Timer timer =
            Metrics
                .timer(
                    SQL_EXECUTE_TIME, Tags
                        .of(Tag.of("category", category.getName()), Tag.of("readonly", getOrDefault(
                            () -> String.valueOf(loggable.getConnectionInformation().getConnection().isReadOnly()),
                            "error")),
                            Tag.of("autocommit",
                                getOrDefault(
                                    () -> String.valueOf(
                                        loggable.getConnectionInformation().getConnection().getAutoCommit()),
                                    "error")),
                            Tag.of("statement", SqlParser.getSqlType(category, loggable.getSqlWithValues())),
                            Tag.of("jdbc",
                                getHost(
                                    loggable.getConnectionInformation().getConnection().getMetaData().getURL())))
                        .and(MicrometerUtil.exceptionAndStatusKey(e)));
        timer.record(timeElapsedNanos, TimeUnit.NANOSECONDS);
    } catch (Throwable ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
Example #11
Source File: MicrometerMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testReportSpan() {
    // prepare
    SpanData spanData = defaultMockSpanData();
    when(spanData.getTags()).thenReturn(Collections.singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT));

    MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
            .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT)
            .build();

    // test
    reporter.reportSpan(spanData);

    // verify
    List<Tag> tags = defaultTags();

    assertEquals(100, (long) registry.find("span").timer().totalTime(TimeUnit.MILLISECONDS));
    assertEquals(1, Metrics.timer("span", tags).count());
}
 
Example #12
Source File: TaskMetrics.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
public void onTaskEnd(TaskExecution taskExecution) {
	if (this.taskSample != null) {
		this.taskSample.stop(Timer.builder(SPRING_CLOUD_TASK_METER)
				.description("Task duration").tags(commonTags(taskExecution))
				.tag(TASK_EXIT_CODE_TAG, "" + taskExecution.getExitCode())
				.tag(TASK_EXCEPTION_TAG,
						(this.exception == null) ? "none"
								: this.exception.getClass().getSimpleName())
				.tag(TASK_STATUS_TAG,
						(this.exception == null) ? STATUS_SUCCESS : STATUS_FAILURE)
				.register(Metrics.globalRegistry));
		this.taskSample = null;
	}

	if (this.longTaskSample != null) {
		this.longTaskSample.stop();
		this.longTaskSample = null;
	}
}
 
Example #13
Source File: JobService.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
private JobRunnable metered(final JobRunnable delegate) {
    return new JobRunnable() {

        @Override
        public JobDefinition getJobDefinition() {
            return delegate.getJobDefinition();
        }

        @Override
        public boolean execute(JobEventPublisher jobEventPublisher) {
            long ts = currentTimeMillis();
            boolean executed = delegate.execute(jobEventPublisher);
            Metrics.gauge(gaugeName(), (currentTimeMillis() - ts) / 1000L);
            return executed;
        }

        private String gaugeName() {
            return "gauge.jobs.runtime." + delegate.getJobDefinition().jobType().toLowerCase();
        }
    };
}
 
Example #14
Source File: MicrometerMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTagAndBaggageLabels() {
    String metricName = "testWithTagAndBaggageLabels";

    // prepare
    SpanData spanData = defaultMockSpanData();
    MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
            .withName(metricName)
            .withBaggageLabel(BAGGAGE_LABEL_NAME, BAGGAGE_LABEL_VALUE)
            .withTagLabel(TAG_LABEL_NAME, TAG_LABEL_VALUE)
            .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT)
            .build();

    // test
    reporter.reportSpan(spanData);

    // verify
    List<Tag> tags = defaultTags();
    tags.add(new ImmutableTag(BAGGAGE_LABEL_NAME, BAGGAGE_LABEL_VALUE));
    tags.add(new ImmutableTag(TAG_LABEL_NAME, TAG_LABEL_VALUE));

    assertEquals(100, (long) registry.find(metricName).timer().totalTime(TimeUnit.MILLISECONDS));
    assertEquals(1, Metrics.timer(metricName, tags).count());
}
 
Example #15
Source File: MicrometerMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testSkipMetricReport() {
    String metricName = "testSkipMetricReport";

    // prepare
    SpanData spanData = defaultMockSpanData();
    MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
            .withName(metricName)
            .withConstLabel("skip", null) // any metric with a null value will cause the reporter to skip
            .build();

    // test
    reporter.reportSpan(spanData);

    // verify
    List<Tag> tags = defaultTags();
    assertEquals(0, Metrics.timer(metricName, tags).count());
}
 
Example #16
Source File: PrometheusMetricsReporterConfiguration.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Bean
public MetricsReporter prometheusMetricsReporter(PrometheusMeterRegistry prometheusMeterRegistry) {
    Metrics.addRegistry(prometheusMeterRegistry);

    MicrometerMetricsReporter.Builder builder = MicrometerMetricsReporter.newMetricsReporter();
    if (metricsName != null && !metricsName.isEmpty()) {
        builder.withName(metricsName);
    }

    if (metricLabels != null && !metricLabels.isEmpty()) {
        for (MetricLabel label : metricLabels) {
            builder.withCustomLabel(label);
        }
    }
    return builder.build();
}
 
Example #17
Source File: ConfSkalogsService.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
public String fetch(String env, String category, String apiKey, String hostname){
    log.error("Call env {} category {} apiKey {} hostname {}",env,category,apiKey,hostname);
    if(checkData(env,category,apiKey,hostname)){
        ConfData confData = ConfData.builder().apiKey(apiKey).category(category).env(env).build();
        Metrics.counter("skaetl_fetch_skalogs_conf",
                Lists.newArrayList(
                        Tag.of("category",category),
                        Tag.of("env", env)
                )
        ).increment();

        updateHost(hostname,env);
        ConfigurationLogstash configFecth = confService.findAll().stream()
                .filter(cl -> cl.getConfData().equals(confData))
                .findFirst().orElse(ConfigurationLogstash.builder().build());
        if(configFecth.statusCustomConfiguration){
            return configFecth.getCustomConfiguration();
        }else{
            return utilsConfig.generateConfig(configFecth);
        }
    }else{
        Metrics.counter("skaetl_fetch_skalogs_conf_error").increment();
        return utilsConfig.generateConfig(ConfigurationLogstash.builder().build());
    }
}
 
Example #18
Source File: AbstractMicrometerTest.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
	Metrics.globalRegistry.getMeters().forEach(Metrics.globalRegistry::remove);
	assertThat(simpleMeterRegistry).isNotNull();
	meter = simpleMeterRegistry.find("spring.integration.handlers").meter();
	assertThat(meter).isNotNull().withFailMessage(
			"The spring.integration.handlers meter must be present in SpringBoot apps!");
}
 
Example #19
Source File: BinderTests.java    From mewbase with MIT License 5 votes vote down vote up
@Test
public void testDelete() throws Exception {
    final String testBinderName = new Object(){}.getClass().getEnclosingMethod().getName();

    singleStoreTest(store -> {

        // Set up instrumentation
        Metrics.addRegistry(new SimpleMeterRegistry());

        Binder binder = store.open(testBinderName);

        BsonObject docPut = createObject();
        assertTrue(binder.put("id1234", docPut).get());
        metricsExpectations(1L,0L,0L,1L,testBinderName);

        BsonObject docGet = binder.get("id1234").get();
        assertEquals(docPut, docGet);
        metricsExpectations(1L,1L,0L,1L,testBinderName);

        assertTrue(binder.delete("id1234").get());
        metricsExpectations(1L,1L,1L,0L,testBinderName);

        docGet = binder.get("id1234").get();
        assertNull(docGet);
        metricsExpectations(1L,2L,1L,0L,testBinderName);
    });

}
 
Example #20
Source File: Bucket4jMetricHandler.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags) {
	
	List<String> extendedTags = new ArrayList<>();
	extendedTags.add("name");
	extendedTags.add(name);
	
	tags
		.stream()
		.filter(tag -> tag.getTypes().contains(type))
		.forEach(metricTagResult -> {
			extendedTags.add(metricTagResult.getKey());
			extendedTags.add(metricTagResult.getValue());
		});
	
	String[] extendedTagsArray = extendedTags.toArray(new String[0]);

	switch(type) {
	case CONSUMED_COUNTER:
		Metrics
			.counter("bucket4j_summary_consumed", extendedTagsArray)
			.increment(tokens);
		break;
	case REJECTED_COUNTER:
		Metrics
		.counter("bucket4j_summary_rejected", extendedTagsArray)
		.increment(tokens);
		break;
	default:
		throw new IllegalStateException("Unsupported metric type: " + type);
	}
	
}
 
Example #21
Source File: JobServiceTest.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
public void shouldReportRuntime() {
    // given:
    when(jobRunnable.getJobDefinition()).thenReturn(someJobDefinition("BAR"));

    // when:
    jobService.startAsyncJob("BAR");
    // then:
    assertThat(Metrics.summary("gauge.jobs.runtime.bar").totalAmount(), is(greaterThan(0.0d)));
}
 
Example #22
Source File: FluxMetricsFuseableTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void queuePollTracksOnNext() {
	//prepare registry with mock clock
	MockClock clock = new MockClock();
	removeRegistry();
	registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock);
	Metrics.globalRegistry.add(registry);

	AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create();
	FluxMetricsFuseable.MetricsFuseableSubscriber<Integer> fuseableSubscriber =
			new FluxMetricsFuseable.MetricsFuseableSubscriber<>(testSubscriber,
					registry, clock, "foo", Tags.empty());

	Fuseable.QueueSubscription<Integer> testQueue = new FluxPeekFuseableTest.AssertQueueSubscription<>();
	testQueue.offer(1);

	fuseableSubscriber.onSubscribe(testQueue);
	clock.add(Duration.ofMillis(200));

	Integer val1 = fuseableSubscriber.poll();
	Integer val2 = fuseableSubscriber.poll();

	assertThat(val1).isEqualTo(1);
	assertThat(val2).isNull();

	//test meters
	Timer nextTimer = registry.find(METER_ON_NEXT_DELAY)
			.timer();

	assertThat(nextTimer).isNotNull();
	assertThat(nextTimer.max(TimeUnit.MILLISECONDS)).as("onNext max delay").isEqualTo(200);
}
 
Example #23
Source File: MeterRegistryConfigurer.java    From foremast with Apache License 2.0 5 votes vote down vote up
void configure(MeterRegistry registry) {
    // Customizers must be applied before binders, as they may add custom
    // tags or alter timer or summary configuration.
    customize(registry);
    addFilters(registry);
    addBinders(registry);
    if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) {
        Metrics.addRegistry(registry);
    }
}
 
Example #24
Source File: MicroMeterMetricCollector.java    From secor with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(SecorConfig config) {
    if (config.getMicroMeterCollectorStatsdEnabled()) {
        MeterRegistry statsdRegistry =
            new StatsdMeterRegistry(StatsdConfig.DEFAULT, Clock.SYSTEM);
        Metrics.addRegistry(statsdRegistry);
    }

    if (config.getMicroMeterCollectorJmxEnabled()) {
        MeterRegistry jmxRegistry = new JmxMeterRegistry(JmxConfig.DEFAULT, Clock.SYSTEM);
        Metrics.addRegistry(jmxRegistry);
    }
}
 
Example #25
Source File: MetricsManager.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
/**
 * Callback used to run the bean.
 *
 * @param args incoming main method arguments
 * @throws Exception on error
 */
@Override
public void run(String... args) throws Exception {

    Metrics.gauge(MetricsStatisticsType.CACHE_SIZE.getMetricsName(), this,
            MetricsManager::getCacheSize
    );
    Metrics.gauge(MetricsStatisticsType.CLUSTER_SIZE.getMetricsName(), this,
            MetricsManager::getClusterSize
    );
    Metrics.gauge(MetricsStatisticsType.TASK_SIZE.getMetricsName(), this,
            MetricsManager::getTaskSize
    );
}
 
Example #26
Source File: TaskMetrics.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
public void onTaskStartup(TaskExecution taskExecution) {
	LongTaskTimer longTaskTimer = LongTaskTimer
			.builder(SPRING_CLOUD_TASK_ACTIVE_METER).description("Long task duration")
			.tags(commonTags(taskExecution)).register(Metrics.globalRegistry);

	this.longTaskSample = longTaskTimer.start();
	this.taskSample = Timer.start(Metrics.globalRegistry);
}
 
Example #27
Source File: FluxMetricsFuseable.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * For testing purposes.
 *
 * @param candidate the registry to use, as a plain {@link Object} to avoid leaking dependency
 */
FluxMetricsFuseable(Flux<? extends T> flux, @Nullable MeterRegistry candidate) {
	super(flux);

	this.name = resolveName(flux);
	this.tags = resolveTags(flux, FluxMetrics.DEFAULT_TAGS_FLUX, this.name);

	if (candidate == null) {
		this.registryCandidate = Metrics.globalRegistry;
	}
	else {
		this.registryCandidate = candidate;
	}
}
 
Example #28
Source File: TaskMetricsTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
	Metrics.globalRegistry.getMeters().forEach(Metrics.globalRegistry::remove);
	simpleMeterRegistry = new SimpleMeterRegistry();
	Metrics.addRegistry(simpleMeterRegistry);
	taskMetrics = new TaskMetrics();
}
 
Example #29
Source File: EventHandlerShim.java    From mewbase with MIT License 5 votes vote down vote up
public EventHandlerShim(String channelName, EventHandler impl) {
    List<Tag> tag = Arrays.asList(Tag.of("channel", channelName));
    // This results in a call down to the meter registry which will either register the counter or
    // return the one currently in scope for this id/tag combination.
    // From the Micrometer MeterRegistry java doc ...
    // Add the counter to a single registry, or return an existing counter in that registry. The returned
    // counter will be unique for each registry, but each registry is guaranteed to only create one counter
    // for the same combination of name and tags.
    eventCounter = Metrics.counter( METRICS_NAME, tag );
    this.impl = impl;
}
 
Example #30
Source File: HttpMetricsHandlerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
	if (disposableServer != null) {
		disposableServer.disposeNow();
	}

	provider.disposeLater()
	        .block(Duration.ofSeconds(30));

	Metrics.removeRegistry(registry);
	registry.clear();
	registry.close();
}