Java Code Examples for io.micrometer.core.instrument.Tags#of()

The following examples show how to use io.micrometer.core.instrument.Tags#of() . 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: MicrometerMetricsPublisherCommandTest.java    From micrometer with Apache License 2.0 7 votes vote down vote up
@Test
void openCircuit() {
    HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
    HystrixPlugins.reset();
    HystrixPlugins.getInstance().registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher));
    HystrixCommandKey key = HystrixCommandKey.Factory.asKey("MicrometerCOMMAND-B");

    propertiesSetter.withCircuitBreakerForceOpen(true);

    new SuccessCommand(key).execute();
    new SuccessCommand(key).execute();
    new TimeoutCommand(key).execute();
    new FailureCommand(key).execute();
    new FailureCommand(key).execute();
    new SuccessCommand(key).execute();

    Iterable<Tag> tags = Tags.of("group", groupKey.name(), "key", key.name());

    assertExecutionMetric(tags, HystrixEventType.SHORT_CIRCUITED, 6.0);
    assertExecutionMetric(tags, HystrixEventType.SUCCESS, 0.0);
    assertExecutionMetric(tags, HystrixEventType.TIMEOUT, 0.0);
    assertExecutionMetric(tags, HystrixEventType.FAILURE, 0.0);
    assertThat(registry.get("hystrix.circuit.breaker.open").tags(tags).gauge().value()).isEqualTo(1.0);
}
 
Example 2
Source File: OkHttpConnectionPoolMetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void activeAndIdle() {
    OkHttpConnectionPoolMetrics instance = new OkHttpConnectionPoolMetrics(connectionPool, Tags.of("foo", "bar"));
    instance.bindTo(registry);
    when(connectionPool.connectionCount()).thenReturn(17);
    when(connectionPool.idleConnectionCount()).thenReturn(10, 9);

    assertThat(registry.get("okhttp.pool.connection.count")
            .tags(Tags.of("foo", "bar", "state", "active"))
            .gauge().value()).isEqualTo(7.0);
    assertThat(registry.get("okhttp.pool.connection.count")
            .tags(Tags.of("foo", "bar", "state", "idle"))
            .gauge().value()).isEqualTo(10.0);

    assertThat(registry.get("okhttp.pool.connection.count")
            .tags(Tags.of("foo", "bar", "state", "active"))
            .gauge().value()).isEqualTo(8.0);
    assertThat(registry.get("okhttp.pool.connection.count")
            .tags(Tags.of("foo", "bar", "state", "idle"))
            .gauge().value()).isEqualTo(9.0);
}
 
Example 3
Source File: TopicOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public void initMetrics() {
    if (metrics != null) {
        Tags metricTags = Tags.of(Tag.of("kind", "KafkaTopic"));

        periodicReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.periodical",
                "Number of periodical reconciliations done by the operator",
                metricTags);

        reconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations",
                "Number of reconciliations done by the operator for individual topics",
                metricTags);

        failedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.failed",
                "Number of reconciliations done by the operator for individual topics which failed",
                metricTags);

        successfulReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.successful",
                "Number of reconciliations done by the operator for individual topics which were successful",
                metricTags);

        topicCounter = metrics.gauge(METRICS_PREFIX + "resources",
                "Number of topics the operator sees",
                metricTags);

        reconciliationsTimer = metrics.timer(METRICS_PREFIX + "reconciliations.duration",
                "The time the reconciliation takes to complete",
                metricTags);

        lockedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.locked",
                "Number of reconciliations skipped because another reconciliation for the same topic was still running",
                metricTags);
    }
}
 
Example 4
Source File: KafkaConsumerMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void returnsNegativeKafkaMajorVersionWhenMBeanInstanceNotFound() {
    try (Consumer<Long, String> consumer = createConsumer()) {
        Tags tags = Tags.of("client.id", "invalid");
        assertThat(kafkaConsumerMetrics.kafkaMajorVersion(tags)).isEqualTo(-1);
    }
}
 
Example 5
Source File: GatewayHttpTagsProvider.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Tags apply(ServerWebExchange exchange) {
	String outcome = "CUSTOM";
	String status = "CUSTOM";
	String httpStatusCodeStr = "NA";

	String httpMethod = exchange.getRequest().getMethodValue();

	// a non standard HTTPS status could be used. Let's be defensive here
	// it needs to be checked for first, otherwise the delegate response
	// who's status DIDN'T change, will be used
	if (exchange.getResponse() instanceof AbstractServerHttpResponse) {
		Integer statusInt = ((AbstractServerHttpResponse) exchange.getResponse())
				.getStatusCodeValue();
		if (statusInt != null) {
			status = String.valueOf(statusInt);
			httpStatusCodeStr = status;
			HttpStatus resolved = HttpStatus.resolve(statusInt);
			if (resolved != null) {
				// this is not a CUSTOM status, so use series here.
				outcome = resolved.series().name();
				status = resolved.name();
			}
		}
	}
	else {
		HttpStatus statusCode = exchange.getResponse().getStatusCode();
		if (statusCode != null) {
			httpStatusCodeStr = String.valueOf(statusCode.value());
			outcome = statusCode.series().name();
			status = statusCode.name();
		}
	}

	return Tags.of("outcome", outcome, "status", status, "httpStatusCode",
			httpStatusCodeStr, "httpMethod", httpMethod);
}
 
Example 6
Source File: MongoMetricsConnectionPoolListenerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCreatePoolMetrics() {
    MeterRegistry registry = new SimpleMeterRegistry();
    AtomicReference<String> clusterId = new AtomicReference<>();
    MongoClientOptions options = MongoClientOptions.builder()
            .minConnectionsPerHost(2)
            .addConnectionPoolListener(new MongoMetricsConnectionPoolListener(registry))
            .addClusterListener(new ClusterListenerAdapter() {
                @Override
                public void clusterOpening(ClusterOpeningEvent event) {
                    clusterId.set(event.getClusterId().getValue());
                }
            })
            .build();
    MongoClient mongo = new MongoClient(new ServerAddress(HOST, port), options);

    mongo.getDatabase("test")
            .createCollection("testCol");

    Tags tags = Tags.of(
            "cluster.id", clusterId.get(),
            "server.address", String.format("%s:%s", HOST, port)
    );

    assertThat(registry.get("mongodb.driver.pool.size").tags(tags).gauge().value()).isEqualTo(2);
    assertThat(registry.get("mongodb.driver.pool.checkedout").gauge().value()).isZero();
    assertThat(registry.get("mongodb.driver.pool.waitqueuesize").gauge().value()).isZero();

    mongo.close();

    assertThat(registry.find("mongodb.driver.pool.size").tags(tags).gauge())
            .describedAs("metrics should be removed when the connection pool is closed")
            .isNull();
}
 
Example 7
Source File: MicrometerMetricsPublisherThreadPool.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public MicrometerMetricsPublisherThreadPool(
    final MeterRegistry meterRegistry,
    final HystrixThreadPoolKey threadPoolKey,
    final HystrixThreadPoolMetrics metrics,
    final HystrixThreadPoolProperties properties,
    final HystrixMetricsPublisherThreadPool metricsPublisherForThreadPool) {
  this.meterRegistry = meterRegistry;
  this.metrics = metrics;
  this.properties = properties;
  this.metricsPublisherForThreadPool = metricsPublisherForThreadPool;

  this.tags = Tags.of("key", threadPoolKey.name());
}
 
Example 8
Source File: MetricsGenerator.java    From kayenta with Apache License 2.0 5 votes vote down vote up
private void createMetricsForScope(String namespace, ScopeMetricsConfiguration scopeConfig) {
  String scope = scopeConfig.getScope();
  Tags tags = Tags.of(Tag.of("scope", scope), Tag.of("namespace", namespace));

  scopeConfig
      .getMetrics()
      .forEach(
          metric -> {
            String metricName = metric.getName();
            switch (metric.getType()) {
              case "gauge":
                registry.gauge(
                    metricName,
                    tags,
                    randomProvider,
                    provider ->
                        provider.getDouble(metric.getLowerBound(), metric.getUpperBound()));
                break;
              case "timer":
                this.timers.put(
                    registry.timer(metricName, tags),
                    provider ->
                        randomProvider.getLong(metric.getLowerBound(), metric.getUpperBound()));
                break;
              default:
                throw new IllegalArgumentException("Unknown metric type for metric: " + metric);
            }
          });
}
 
Example 9
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 10
Source File: MongoMetricsCommandListenerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCreateFailedCommandMetric() {
    mongo.getDatabase("test")
            .getCollection("testCol")
            .dropIndex("nonExistentIndex");

    Tags tags = Tags.of(
            "cluster.id", clusterId.get(),
            "server.address", String.format("%s:%s", HOST, port),
            "command", "dropIndexes",
            "status", "FAILED"
    );
    assertThat(registry.get("mongodb.driver.commands").tags(tags).timer().count()).isEqualTo(1);
}
 
Example 11
Source File: PropertiesMeterFilter.java    From foremast with Apache License 2.0 5 votes vote down vote up
private static MeterFilter createMapFilter(Map<String, String> tags) {
    if (tags.isEmpty()) {
        return new MeterFilter() {
        };
    }
    Tags commonTags = Tags.of(tags.entrySet().stream()
            .map((entry) -> Tag.of(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList()));
    return MeterFilter.commonTags(commonTags);
}
 
Example 12
Source File: AbstractGatewayRSocket.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
protected Tags getTags(GatewayExchange exchange) {
	// TODO: add tags to exchange
	String requesterName = "FIXME"; // FIXME: this.metadata.get(SERVICE_NAME);
	String requesterId = "FIXME"; // FIXME: this.metadata.getRouteId();
	String responderName = "FIXME"; // FIXME: exchange.getRoutingMetadata().getName();
	Assert.hasText(responderName, "responderName must not be empty");
	Assert.hasText(requesterId, "requesterId must not be empty");
	Assert.hasText(requesterName, "requesterName must not be empty");
	// responder.id happens in a callback, later
	return Tags.of("requester.name", requesterName, "responder.name", responderName,
			"requester.id", requesterId, "gateway.id", this.properties.getId());
}
 
Example 13
Source File: MetricServiceBean.java    From spring-batch-lightmin with Apache License 2.0 4 votes vote down vote up
@Override
public void measureStepExecution(final LightminMetricSource source, final StepExecutionEventInfo stepExecutionEventInfo) {
    requireNonNull(this.registry, "registry");

    // ExitStatus of Job is UNKNOWN while steps are in Execution
    final Tags tags = Tags.of(
            Tag.of(TAG_NAME, stepExecutionEventInfo.getStepName()),
            Tag.of(TAG_STATUS, stepExecutionEventInfo.getExitStatus().getExitCode()),
            Tag.of(TAG_JOBNAME, stepExecutionEventInfo.getJobName()),
            Tag.of(TAG_APPNAME, stepExecutionEventInfo.getApplicationName()));

    //Case FAILED

    if (LightminExitStatus.FAILED.getExitCode().equals(stepExecutionEventInfo.getExitStatus().getExitCode())) {

        final String dataRollback = LightminMetricUtils.getMetricNameOrNull(source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_ROLLBACK);

        if (!isNull(dataRollback)) {
            Gauge.builder(dataRollback, stepExecutionEventInfo.getRollbackCount(), Integer::doubleValue)
                    .tags(tags)
                    .strongReference(true)
                    .register(this.registry);
        } else {
            log.info("{}_{} is unknown by Lightmin Context and is therefore not created.", source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_ROLLBACK);
        }
    } else {
        log.trace("Nothing to handle for ExitCode FAILED");
    }

    final String dataRead = LightminMetricUtils.getMetricNameOrNull(source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_READ);

    if (!isNull(dataRead)) {
        Gauge.builder(dataRead, stepExecutionEventInfo.getReadCount(), Integer::doubleValue)
                .tags(tags)
                .strongReference(true)
                .register(this.registry);
    } else {
        log.info("{}_{} is unknown by Lightmin Context and is therefore not created.", source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_READ);
    }
    final String dataWrite = LightminMetricUtils.getMetricNameOrNull(source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_WRITE);

    if (!isNull(dataWrite)) {
        Gauge.builder(dataWrite, stepExecutionEventInfo.getWriteCount(), Integer::doubleValue)
                .tags(tags)
                .strongReference(true)
                .register(this.registry);
    } else {
        log.info("{}_{} is unknown by Lightmin Context and is therefore not created.", source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_WRITE);
    }
    final String dataCommit = LightminMetricUtils.getMetricNameOrNull(source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_WRITE);

    if (!isNull(dataCommit)) {
        Gauge.builder(dataCommit, stepExecutionEventInfo.getCommitCount(), Integer::doubleValue)
                .tags(tags)
                .strongReference(true)
                .register(this.registry);
    } else {
        log.info("{}_{} is unknown by Lightmin Context and is therefore not created.", source, LightminMetricUtils.LightminMetrics.LIGHTMIN_STEP_DATA_WRITE);
    }
}
 
Example 14
Source File: SofaRpcMetrics.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public SofaRpcMetrics(Iterable<Tag> common) {
    this.common = Tags.of(common);
    register();
}
 
Example 15
Source File: CallerWebMvcTagsProvider.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) {
    return Tags.of(new Tag[]{WebMvcTags.method(request), WebMvcTags.uri(request, response), WebMvcTags.exception(exception), WebMvcTags.status(response), caller(request)});
}
 
Example 16
Source File: DefaultJerseyTagsProvider.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<Tag> httpLongRequestTags(RequestEvent event) {
    return Tags.of(JerseyTags.method(event.getContainerRequest()), JerseyTags.uri(event));
}
 
Example 17
Source File: OkHttpConnectionPoolMetricsTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Test
void instanceUsesGivenNamePrefixAndTag() {
    OkHttpConnectionPoolMetrics instance = new OkHttpConnectionPoolMetrics(connectionPool, "another.meter", Tags.of("bar", "baz"));
    instance.bindTo(registry);
    registry.get("another.meter.connection.count").tags("bar", "baz"); // does not throw MeterNotFoundException
}
 
Example 18
Source File: MicrometerUtil.java    From summerframework with Apache License 2.0 4 votes vote down vote up
public static Tags exceptionAndStatusKey(@Nullable Throwable exception) {
    return Tags.of(exception(exception), statusKey(exception));
}
 
Example 19
Source File: SchedulerMetricDecorator.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized ScheduledExecutorService apply(Scheduler scheduler, ScheduledExecutorService service) {
	//this is equivalent to `toString`, a detailed name like `parallel("foo", 3)`
	String schedulerName = Scannable
			.from(scheduler)
			.scanOrDefault(Attr.NAME, scheduler.getClass().getName());

	//we hope that each NAME is unique enough, but we'll differentiate by Scheduler
	String schedulerId =
			seenSchedulers.computeIfAbsent(scheduler, s -> {
				int schedulerDifferentiator = this.schedulerDifferentiator
						.computeIfAbsent(schedulerName, k -> new AtomicInteger(0))
						.getAndIncrement();

				return (schedulerDifferentiator == 0) ? schedulerName
						: schedulerName + "#" + schedulerDifferentiator;
			});

	//we now want an executorId unique to a given scheduler
	String executorId = schedulerId + "-" +
			executorDifferentiator.computeIfAbsent(scheduler, key -> new AtomicInteger(0))
			                      .getAndIncrement();

	Tags tags = Tags.of(TAG_SCHEDULER_ID, schedulerId);

	/*
	Design note: we assume that a given Scheduler won't apply the decorator twice to the
	same ExecutorService. Even though, it would simply create an extraneous meter for
	that ExecutorService, which we think is not that bad (compared to paying the price
	upfront of also tracking executors instances to deduplicate). The main goal is to
	detect Scheduler instances that have already started decorating their executors,
	in order to avoid consider two calls in a row as duplicates (yet still being able
	to distinguish between two instances with the same name and configuration).
	 */

	class MetricsRemovingScheduledExecutorService extends DelegatingScheduledExecutorService {

		MetricsRemovingScheduledExecutorService() {
			super(ExecutorServiceMetrics.monitor(globalRegistry, service, executorId, tags));
		}

		@Override
		public List<Runnable> shutdownNow() {
			removeMetrics();
			return super.shutdownNow();
		}

		@Override
		public void shutdown() {
			removeMetrics();
			super.shutdown();
		}

		void removeMetrics() {
			Search.in(globalRegistry)
			      .tag("name", executorId)
			      .meters()
			      .forEach(globalRegistry::remove);
		}
	}
	return new MetricsRemovingScheduledExecutorService();
}
 
Example 20
Source File: CountedAspect.java    From micrometer with Apache License 2.0 2 votes vote down vote up
/**
 * Construct a new aspect with the given {@code meterRegistry} along with a default
 * tags provider.
 *
 * @param meterRegistry Where we're going register metrics.
 */
public CountedAspect(MeterRegistry meterRegistry) {
    this(meterRegistry, pjp ->
            Tags.of("class", pjp.getStaticPart().getSignature().getDeclaringTypeName(),
                    "method", pjp.getStaticPart().getSignature().getName()));
}