io.micrometer.core.instrument.Tag Java Examples

The following examples show how to use io.micrometer.core.instrument.Tag. 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: UserAgentMetricFilter.java    From data-highway with Apache License 2.0 7 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {
  if (request instanceof HttpServletRequest) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String roadName = template.match(httpRequest.getRequestURI()).get("name");
    UserAgent userAgent = UserAgent.parse(httpRequest.getHeader("User-Agent"));
    products.forEach(product -> {
      userAgent.token(product).ifPresent(token -> {
        String version = token.getVersion().replaceAll("\\.", "-");
        Tag roadTag = Tag.of("road", roadName);
        Tag productTag = Tag.of("product", product);
        Tag versionTag = Tag.of("version", version);
        ImmutableList<Tag> tags = ImmutableList.of(roadTag, productTag, versionTag);
        registry.counter("user-agent-metric-filter", tags).increment();
      });
    });
  }
  chain.doFilter(request, response);
}
 
Example #3
Source File: DiskSpaceMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    Iterable<Tag> tagsWithPath = Tags.concat(tags, "path", absolutePath);
    Gauge.builder("disk.free", path, File::getUsableSpace)
            .tags(tagsWithPath)
            .description("Usable space for path")
            .baseUnit(BaseUnits.BYTES)
            .strongReference(true)
            .register(registry);
    Gauge.builder("disk.total", path, File::getTotalSpace)
            .tags(tagsWithPath)
            .description("Total space for path")
            .baseUnit(BaseUnits.BYTES)
            .strongReference(true)
            .register(registry);
}
 
Example #4
Source File: KafkaMetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Issue("#1968")
@Test
void shouldRemoveOlderMeterWithLessTagsWhenCommonTagsConfigured() {
    //Given
    Map<String, String> tags = new LinkedHashMap<>();
    Supplier<Map<MetricName, ? extends Metric>> supplier = () -> {
        MetricName metricName = new MetricName("a", "b", "c", tags);
        KafkaMetric metric = new KafkaMetric(this, metricName, new Value(), new MetricConfig(), Time.SYSTEM);
        return Collections.singletonMap(metricName, metric);
    };

    kafkaMetrics = new KafkaMetrics(supplier);
    MeterRegistry registry = new SimpleMeterRegistry();
    registry.config().commonTags("common", "value");

    kafkaMetrics.bindTo(registry);
    assertThat(registry.getMeters()).hasSize(1);
    assertThat(registry.getMeters().get(0).getId().getTags()).containsExactlyInAnyOrder(Tag.of("kafka-version", "unknown"), Tag.of("common", "value")); // only version

    tags.put("key0", "value0");
    kafkaMetrics.checkAndBindMetrics(registry);
    assertThat(registry.getMeters()).hasSize(1);
    assertThat(registry.getMeters().get(0).getId().getTags()).containsExactlyInAnyOrder(Tag.of("kafka-version", "unknown"), Tag.of("key0", "value0"), Tag.of("common", "value"));
}
 
Example #5
Source File: WebMvcTags.java    From foremast with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the
 * {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if
 * available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND}
 * for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
 * for all other requests.
 *
 * @param request the request
 * @param response the response
 * @return the uri tag derived from the request
 */
public static Tag uri(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response) {
    if (request != null) {
        String pattern = getMatchingPattern(request);
        if (pattern != null) {
            return Tag.of("uri", pattern);
        } else if (response != null) {
            HttpStatus status = extractStatus(response);
            if (status != null && status.is3xxRedirection()) {
                return URI_REDIRECTION;
            }
            if (status != null && status.equals(HttpStatus.NOT_FOUND)) {
                return URI_NOT_FOUND;
            }
        }
        String pathInfo = getPathInfo(request);
        if (pathInfo.isEmpty()) {
            return URI_ROOT;
        }
    }
    return URI_UNKNOWN;
}
 
Example #6
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 #7
Source File: JettyClientMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void onQueued(Request request) {
    Timer.Sample sample = Timer.start(registry);

    request.onComplete(result -> {
        long requestLength = result.getRequest().getContent().getLength();
        Iterable<Tag> httpRequestTags = tagsProvider.httpRequestTags(result);
        if (requestLength >= 0) {
            DistributionSummary.builder(contentSizeMetricName)
                    .description("Content sizes for Jetty HTTP client requests")
                    .tags(httpRequestTags)
                    .register(registry)
                    .record(requestLength);
        }

        sample.stop(Timer.builder(timingMetricName)
                .description("Jetty HTTP client request timing")
                .tags(httpRequestTags)
                .register(registry));
    });
}
 
Example #8
Source File: WebMvcTags.java    From foremast with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the
 * {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if
 * available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND}
 * for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
 * for all other requests.
 *
 * @param request the request
 * @param response the response
 * @return the uri tag derived from the request
 */
public static Tag uri(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response) {
    if (request != null) {
        String pattern = getMatchingPattern(request);
        if (pattern != null) {
            return Tag.of("uri", pattern);
        } else if (response != null) {
            HttpStatus status = extractStatus(response);
            if (status != null && status.is3xxRedirection()) {
                return URI_REDIRECTION;
            }
            if (status != null && status.equals(HttpStatus.NOT_FOUND)) {
                return URI_NOT_FOUND;
            }
        }
        String pathInfo = getPathInfo(request);
        if (pathInfo.isEmpty()) {
            return URI_ROOT;
        }
    }
    return URI_UNKNOWN;
}
 
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: MicrometerResponderRSocket.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RSocket}.
 * @param delegate the {@link RSocket} to delegate to
 * @param meterRegistry the {@link MeterRegistry} to use
 * @param tags additional tags to attach to {@link Meter}s
 * @throws IllegalArgumentException if {@code delegate} or {@code meterRegistry} is
 * {@code null}
 */
public MicrometerResponderRSocket(RSocket delegate, MeterRegistry meterRegistry,
		Tag... tags) {
	Assert.notNull(delegate, "delegate must not be null");
	Assert.notNull(meterRegistry, "meterRegistry must not be null");

	this.delegate = delegate;
	this.metadataPush = new InteractionCounters(meterRegistry, "metadata.push", tags);
	this.requestChannel = new InteractionCounters(meterRegistry, "request.channel",
			tags);
	this.requestFireAndForget = new InteractionCounters(meterRegistry, "request.fnf",
			tags);
	this.requestResponse = new InteractionTimers(meterRegistry, "request.response",
			tags);
	this.requestStream = new InteractionCounters(meterRegistry, "request.stream",
			tags);
}
 
Example #11
Source File: MicrometerMetricsReporterTest.java    From java-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testOverriddenTagAndBaggageLabels() {
    String metricName = "testOverriddenTagAndBaggageLabels";

    // prepare
    SpanData spanData = defaultMockSpanData();
    when(spanData.getBaggageItem(BAGGAGE_LABEL_NAME)).thenReturn("NewBaggageValue");
    when(spanData.getTags()).thenReturn(Collections.singletonMap(TAG_LABEL_NAME, "NewTagValue"));

    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, "NewBaggageValue"));
    tags.add(new ImmutableTag(TAG_LABEL_NAME, "NewTagValue"));

    assertEquals(100, (long) registry.find(metricName).timer().totalTime(TimeUnit.MILLISECONDS));
    assertEquals(1, Metrics.timer(metricName, tags).count());
}
 
Example #12
Source File: MicrometerResponderRSocket.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
private Counter counter(MeterRegistry meterRegistry, String interactionModel,
		SignalType signalType, Tag... tags) {

	Tags withType = Tags.of(tags).and("signal.type", signalType.name());
	try {
		return meterRegistry.counter("rsocket." + interactionModel, withType);
	}
	catch (Exception e) {
		if (log.isTraceEnabled()) {
			log.trace("Error creating counter with tags: " + withType, e);
		}
		return null;
	}
}
 
Example #13
Source File: GenericValidator.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public ValidateData mandatoryImporter(ObjectNode jsonValue) {
    //JSON
    if (jsonValue == null) {
        Metrics.counter("skaetl_nb_mandatory_importer", Lists.newArrayList(Tag.of("type", "jsonFormat"))).increment();
        return UtilsValidateData.createValidateData(false, StatusCode.invalid_json, TypeValidation.FORMAT_JSON, jsonValue);
    }
    //PROJECT
    String project = jsonValue.path("project").asText();
    if (StringUtils.isBlank(project)) {
        Metrics.counter("skaetl_nb_mandatory_importer", Lists.newArrayList(Tag.of("type", "project"))).increment();
        return UtilsValidateData.createValidateData(false, StatusCode.missing_mandatory_field_project, TypeValidation.MANDATORY_FIELD, jsonValue, "missing project");
    }
    //TYPE
    String type = jsonValue.path("type").asText();
    if (StringUtils.isBlank(type)) {
        Metrics.counter("skaetl_nb_mandatory_importer", Lists.newArrayList(Tag.of("type", "type"))).increment();
        return UtilsValidateData.createValidateData(false, StatusCode.missing_mandatory_field_type, TypeValidation.MANDATORY_FIELD, jsonValue, "missing type");
    }
    //TIMESTAMP
    String timestampAnnotedAsString = jsonValue.path("@timestamp").asText();
    String timestampAsString = jsonValue.path("timestamp").asText();

    if (StringUtils.isBlank(timestampAsString) && StringUtils.isBlank(timestampAnnotedAsString)) {
        return UtilsValidateData.createValidateData(project, type, false, StatusCode.missing_timestamp, TypeValidation.MANDATORY_FIELD, jsonValue);
    }

    Date timestamp;
    try {
        if (StringUtils.isBlank(timestampAsString)) {
            timestamp = dateFormat.parse(timestampAnnotedAsString);
            jsonValue.set("timestamp", jsonValue.path("@timestamp"));
        } else {
            timestamp = dateFormat.parse(timestampAsString);
        }
    } catch (ParseException e) {
        return UtilsValidateData.createValidateData(jsonValue, project, type, false, StatusCode.invalid_format_timestamp, TypeValidation.MANDATORY_FIELD);
    }
    return UtilsValidateData.createValidateData(jsonValue, timestamp, project, type, true);
}
 
Example #14
Source File: JettySslHandshakeMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public JettySslHandshakeMetrics(MeterRegistry registry, Iterable<Tag> tags) {
    this.registry = registry;
    this.tags = tags;

    this.handshakesFailed = Counter.builder(METER_NAME)
            .baseUnit(BaseUnits.EVENTS)
            .description(DESCRIPTION)
            .tag(TAG_RESULT, "failed")
            .tag(TAG_PROTOCOL, TAG_VALUE_UNKNOWN)
            .tag(TAG_CIPHER_SUITE, TAG_VALUE_UNKNOWN)
            .tags(tags)
            .register(registry);
}
 
Example #15
Source File: CrnkWebMvcTagsProviderTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private String getUriTag(Iterable<Tag> tags) {
	for (Tag tag : tags) {
		if (tag.getKey().equals("uri")) {
			return tag.getValue();
		}
	}
	throw new IllegalStateException();
}
 
Example #16
Source File: KafkaConsumerMetrics.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private Iterable<Tag> nameTag(ObjectName name) {
    Tags tags = Tags.empty();

    String clientId = name.getKeyProperty("client-id");
    if (clientId != null) {
        tags = Tags.concat(tags, "client.id", clientId);
    }

    String topic = name.getKeyProperty("topic");
    if (topic != null) {
        tags = Tags.concat(tags, "topic", topic);
    }

    return tags;
}
 
Example #17
Source File: WeighBridgeMetricsTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void typical() throws Exception {
  PartitionReplica replica = new PartitionReplica(1, true, false, 3L, 2L, 4L, 5L, 1L);
  List<PartitionReplica> replicas = singletonList(replica);
  Topic topic = new Topic("topicName", Duration.ofMillis(2L), replicas);
  LogDir logDir = new LogDir("path", 1L, 3L, singletonList(topic));
  List<LogDir> logDirs = singletonList(logDir);
  Broker broker = new Broker(0, "rack", logDirs);

  underTest.update(broker);

  Matcher<Iterable<? extends Tag>> diskTags = containsInAnyOrder(tag("broker", "0"), tag("logdir", "path"),
      tag("rack", "rack"));
  Matcher<Iterable<? extends Tag>> replicaTags = containsInAnyOrder(tag("broker", "0"), tag("logdir", "path"),
      tag("rack", "rack"), tag("topic", "topicName"), tag("partition", "1"), tag("leader", "true"),
      tag("inSync", "false"));

  assertMeter(registry.get("weighbridge_disk_free").meter(), diskTags, 1.0);
  assertMeter(registry.get("weighbridge_disk_total").meter(), diskTags, 3.0);
  assertMeter(registry.get("weighbridge_disk_used").meter(), diskTags, 2.0);
  assertMeter(registry.get("weighbridge_size_on_disk").meter(), replicaTags, 3.0);
  assertMeter(registry.get("weighbridge_log_size").meter(), replicaTags, 2.0);
  assertMeter(registry.get("weighbridge_beginning_offset").meter(), replicaTags, 4.0);
  assertMeter(registry.get("weighbridge_end_offset").meter(), replicaTags, 5.0);
  assertMeter(registry.get("weighbridge_record_count").meter(), replicaTags, 1.0);
}
 
Example #18
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 #19
Source File: MicrometerResponderRSocketInterceptor.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link RSocketInterceptor}.
 * @param meterRegistry the {@link MeterRegistry} to use to create {@link Meter}s.
 * @param tags the additional tags to attach to each {@link Meter}
 * @throws NullPointerException if {@code meterRegistry} is {@code null}
 */
public MicrometerResponderRSocketInterceptor(MeterRegistry meterRegistry,
		Tag... tags) {
	this.meterRegistry = Objects.requireNonNull(meterRegistry,
			"meterRegistry must not be null");
	this.tags = tags;
}
 
Example #20
Source File: RedisAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    if (jedisConnectionFactoryMap == null) {
        return;
    }
    jedisConnectionFactoryMap.forEach((k, v) -> {
        HashSet<Tag> tags = new HashSet<>();
        tags.addAll(platformTag.getTags());
        tags.add(Tag.of("name", k));
        new RedisPoolMeterBinder(platformTag.getTags(), v).bindTo(registry);
    });
}
 
Example #21
Source File: KafkaMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void bindMeter(MeterRegistry registry, Metric metric, String name, Iterable<Tag> tags) {
    if (name.endsWith("total") || name.endsWith("count")) {
        registerCounter(registry, metric, name, tags);
    } else {
        registerGauge(registry, metric, name, tags);
    }
}
 
Example #22
Source File: Rebalancer.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
    log.info("On Partition assigned");
    for (TopicPartition partition : partitions) {
        Metrics.counter("skaetl_nb_partition_assigned_count",
                Lists.newArrayList(
                        Tag.of("topic",partition.topic()),
                        Tag.of("partition",String.valueOf(partition.partition()))
                )
        ).increment();
    }
}
 
Example #23
Source File: MicrometerResponderRSocket.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
private InteractionTimers(MeterRegistry meterRegistry, String interactionModel,
		Tag... tags) {
	this.meterRegistry = meterRegistry;

	this.cancel = timer(meterRegistry, interactionModel, CANCEL, tags);
	this.onComplete = timer(meterRegistry, interactionModel, ON_COMPLETE, tags);
	this.onError = timer(meterRegistry, interactionModel, ON_ERROR, tags);
}
 
Example #24
Source File: MysqlStatusBinder.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public MysqlStatusBinder(DataSource dataSource, String dataSourceName, Iterable<Tag> tags,
    Set<String> variableNames) {
    this.dataSource = dataSource;
    this.dataSourceName = dataSourceName;
    this.tags = tags;
    this.variableNames = variableNames.stream().map(String::toLowerCase).collect(Collectors.toSet());
}
 
Example #25
Source File: RabbitMetricsBinder.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public RabbitMetricsBinder(AbstractConnectionFactory connectionFactory, Iterable<Tag> tags) {
    this.mBeanServer = getMBeanServer();
    this.tags = tags;
    com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = connectionFactory.getRabbitConnectionFactory();
    String metricsPrefix = "rabbit";

    this.connections = Metrics.gauge((metricsPrefix + ".connections"), new AtomicInteger(0));
    this.channels = Metrics.gauge((metricsPrefix + ".channels"), new AtomicInteger(0));
    this.publishedMessages = Metrics.gauge((metricsPrefix + ".published"), new AtomicInteger(0));
    this.consumedMessages = Metrics.gauge((metricsPrefix + ".consumed"), new AtomicInteger(0));
    this.acknowledgedMessages = Metrics.gauge((metricsPrefix + ".acknowledged"), new AtomicInteger(0));
    this.rejectedMessages = Metrics.gauge((metricsPrefix + ".rejected"), new AtomicInteger(0));

    rabbitConnectionFactory.setMetricsCollector(this);
}
 
Example #26
Source File: DiskSpaceMetrics.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    Iterable<Tag> tagsWithPath = Tags.concat(tags, "path", absolutePath);
    Gauge.builder("disk.free", path, File::getUsableSpace).tags(tagsWithPath).description("Usable space for path")
        .baseUnit("bytes").register(registry);
    Gauge.builder("disk.total", path, File::getTotalSpace).tags(tagsWithPath).description("Total space for path")
        .baseUnit("bytes").register(registry);
}
 
Example #27
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 #28
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void routeTaggedIfEnabled(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    HttpClient client = client(executor(true));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    List<String> tagKeys = registry.get(EXPECTED_METER_NAME)
            .timer().getId().getTags().stream()
            .map(Tag::getKey)
            .collect(Collectors.toList());
    assertThat(tagKeys).contains("target.scheme", "target.host", "target.port");
}
 
Example #29
Source File: AbstractKafkaMetricsReporter.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
private Function<MetricName, List<Tag>> getTagFunction() {
    return metricName -> metricName
            .tags()
            .entrySet()
            .stream()
            .filter(entry -> getIncludedTags().contains(entry.getKey()))
            .map(entry -> Tag.of(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());
}
 
Example #30
Source File: HibernateMetricsBinder.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param meterRegistryProvider The meter registry provider
 * @param tags The tags
 */
public HibernateMetricsBinder(
        Provider<MeterRegistry> meterRegistryProvider,
        @Property(name = MICRONAUT_METRICS_BINDERS + ".hibernate.tags")
        @MapFormat(transformation = MapFormat.MapTransformation.FLAT)
        Map<String, String> tags) {
    this.meterRegistryProvider = meterRegistryProvider;
    if (CollectionUtils.isNotEmpty(tags)) {
        this.tags = tags.entrySet().stream().map(entry -> Tag.of(entry.getKey(), entry.getValue())).collect(Collectors.toList());
    } else {
        this.tags = Collections.emptyList();
    }

}