Java Code Examples for io.micrometer.core.instrument.Tag

The following examples show how to use io.micrometer.core.instrument.Tag. These examples are extracted from open source projects. 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
@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 Project: data-highway   Source File: UserAgentMetricFilter.java    License: 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 Project: micrometer   Source File: DiskSpaceMetrics.java    License: 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 Project: micrometer   Source File: KafkaMetricsTest.java    License: 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
@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 6
Source Project: summerframework   Source File: OpenfeignMetricsBinder.java    License: 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 7
Source Project: foremast   Source File: WebMvcTags.java    License: 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 8
/**
 * 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 9
Source Project: micrometer   Source File: JettyClientMetrics.java    License: 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 10
Source Project: foremast   Source File: WebMvcTags.java    License: 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 11
Source Project: data-highway   Source File: WeighBridgeMetricsTest.java    License: 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 12
Source Project: SkaETL   Source File: ESErrorRetryWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void sendToRetryTopic(String applicationId, JsonNode jsonNode) {
    Metrics.counter("skaetl_nb_produce_message_kafka_count",
            Lists.newArrayList(
                    Tag.of("processConsumerName", applicationId),
                    Tag.of("topic", kafkaConfiguration.getRetryTopic()),
                    Tag.of("type", jsonNode.path("type").asText())
            )
    ).increment();
    retryProducer.send(new ProducerRecord<>(kafkaConfiguration.getRetryTopic(), jsonNode));
}
 
Example 13
Source Project: foremast   Source File: PropertiesMeterFilter.java    License: 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 14
Source Project: data-highway   Source File: MessagesMetricSet.java    License: Apache License 2.0 5 votes vote down vote up
public MessagesMetricSet(MeterRegistry registry) {
  receiverErrors = Counter.builder("highwaypatrol-receiverErrors").register(registry);
  transitTime = Timer.builder("highwaypatrol-transitTime").maximumExpectedValue(Duration.ofMinutes(10L)).publishPercentileHistogram().register(registry);
  onrampTime = Timer.builder("highwaypatrol-onrampTime").maximumExpectedValue(Duration.ofMinutes(10L)).publishPercentileHistogram().register(registry);
  messagesCounted = Counter.builder("highwaypatrol-messagesCounted").register(registry);

  messageEndStateReservoirs = new EnumMap<>(MessageState.class);
  for (MessageState state : MessageState.values()) {
    messageEndStateReservoirs
        .put(state, registry.counter("highwaypatrol-endState", singleton(Tag.of("state", state.getMetricName()))));
  }
}
 
Example 15
Source Project: foremast   Source File: PropertiesMeterFilter.java    License: 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 16
Source Project: data-highway   Source File: SecurityMetrics.java    License: Apache License 2.0 5 votes vote down vote up
public void increment(String roadName, AuthenticationType type, AuthorisationOutcome outcome) {
  ImmutableList<Tag> tags = ImmutableList
      .<Tag> builder()
      .add(Tag.of("road", roadName))
      .add(Tag.of("authentication", type.name()))
      .add(Tag.of("authorisation", outcome.name()))
      .build();
  registry.counter(counterName, tags).increment();
}
 
Example 17
Source Project: data-highway   Source File: SecurityMetricsTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testName() throws Exception {
  Counter counter = mock(Counter.class);
  doReturn(counter).when(registry).counter(eq("counterName"), any(Iterable.class));

  underTest.increment("road", AUTHENTICATED, AUTHORISED);

  ArgumentCaptor<Iterable<Tag>> captor = ArgumentCaptor.forClass(Iterable.class);
  verify(registry).counter(eq("counterName"), captor.capture());
  verify(counter).increment();

  Iterable<Tag> tags = captor.getValue();
  assertThat(tags, hasItems(Tag.of("road", "road"), Tag.of("authentication", "AUTHENTICATED"),
      Tag.of("authorisation", "AUTHORISED")));
}
 
Example 18
Source Project: micrometer   Source File: LogbackMetrics.java    License: Apache License 2.0 5 votes vote down vote up
MetricsTurboFilter(MeterRegistry registry, Iterable<Tag> tags) {
    errorCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "error")
            .description("Number of error level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    warnCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "warn")
            .description("Number of warn level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    infoCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "info")
            .description("Number of info level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    debugCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "debug")
            .description("Number of debug level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    traceCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "trace")
            .description("Number of trace level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);
}
 
Example 19
Source Project: syndesis   Source File: EndpointMetricsFilter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Called after the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    Sample sample = (Sample) requestContext.getProperty(TIMING_SAMPLE);
    if (sample != null) {
        List<Tag> tags = new ArrayList<Tag>();
        tags.add(Tag.of("method", getMethod(requestContext)));
        tags.add(Tag.of("status", getStatus(responseContext)));
        tags.add(Tag.of("uri", getUri()));
        sample.stop(registry.timer("http.meta.requests", tags));
    }
}
 
Example 20
Source Project: influx-proxy   Source File: MyRegistryCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Meter.Id map(Meter.Id id) {
    if (null == tagKeys || tagKeys.size() == 0) {
        return id;
    }
    List<Tag> tags = stream(id.getTagsAsIterable().spliterator(), false).filter(t -> {
        for (String tagKey : tagKeys) {
            if (t.getKey().equals(tagKey))
                return false;
        }
        return true;
    }).collect(toList());

    return id.replaceTags(tags);
}
 
Example 21
Source Project: influx-proxy   Source File: PlatformTag.java    License: Apache License 2.0 5 votes vote down vote up
public List<Tag> getTags() {
    if (tags == null) {
        tags = Arrays.asList(Tag.of("application.name", applicationName),
            Tag.of("application.group", applicationGroup), Tag.of("application.version", applicationVersion),
            Tag.of("application.profiles.active", activeProfiles), Tag.of("zone", getEurekaZone()),
            Tag.of("ip", inetUtils.findFirstNonLoopbackHostInfo().getIpAddress()));
    }
    return tags;
}
 
Example 22
Source Project: foremast   Source File: DefaultWebMvcTagsProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Supplies default tags to the Web MVC server programming model.
 *
 * @param request  The HTTP request.
 * @param response The HTTP response.
 * @param ex       The current exception, if any
 * @return A set of tags added to every Spring MVC HTTP request.
 */
@Override
public Iterable<Tag> httpRequestTags(@Nullable HttpServletRequest request,
                                     @Nullable HttpServletResponse response,
                                     @Nullable Object handler,
                                     @Nullable Throwable ex) {
    return Arrays.asList(WebMvcTags.method(request), WebMvcTags.uri(request, response),
        WebMvcTags.exception(ex), WebMvcTags.status(response));
}
 
Example 23
Source Project: micrometer   Source File: JerseyTags.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@code status} tag based on the status of the given {@code response}.
 * @param response the container response
 * @return the status tag derived from the status of the response
 */
public static Tag status(ContainerResponse response) {
    /* In case there is no response we are dealing with an unmapped exception. */
    return (response != null)
            ? Tag.of("status", Integer.toString(response.getStatus()))
            : STATUS_SERVER_ERROR;
}
 
Example 24
Source Project: Moss   Source File: MossMetricsEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<Meter> findFirstMatchingMeters(CompositeMeterRegistry composite,
                                                  String name, Iterable<Tag> tags) {
    return composite.getRegistries().stream()
            .map((registry) -> findFirstMatchingMeters(registry, name, tags))
            .filter((matching) -> !matching.isEmpty()).findFirst()
            .orElse(Collections.emptyList());
}
 
Example 25
Source Project: micronaut-sql   Source File: HibernateMetricsBinder.java    License: 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();
    }

}
 
Example 26
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 27
@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 28
Source Project: kayenta   Source File: MetricsGenerator.java    License: 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 29
Source Project: summerframework   Source File: DiskSpaceMetrics.java    License: 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 30
Source Project: summerframework   Source File: RabbitMetricsBinder.java    License: 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);
}