io.micrometer.core.instrument.Tags Java Examples

The following examples show how to use io.micrometer.core.instrument.Tags. 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: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void uriTagWorksWithUriMapper(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    OkHttpClient client = new OkHttpClient.Builder()
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .uriMapper(req -> req.url().encodedPath())
                    .tags(Tags.of("foo", "bar"))
                    .build())
            .build();

    Request request = new Request.Builder()
            .url(server.baseUrl() + "/helloworld.txt")
            .build();

    client.newCall(request).execute().close();

    assertThat(registry.get("okhttp.requests")
            .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200",
                    "target.host", "localhost",
                    "target.port", String.valueOf(server.port()),
                    "target.scheme", "http")
            .timer().count()).isEqualTo(1L);
}
 
Example #2
Source File: MonoMetricsFuseableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void requestFusionDelegates() {
	AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create();
	MetricsFuseableSubscriber<Integer> fuseableSubscriber =
			new MetricsFuseableSubscriber<>(testSubscriber,
					registry, Clock.SYSTEM, Tags.empty());

	Fuseable.QueueSubscription<Integer> testQueue = new FluxPeekFuseableTest.AssertQueueSubscription<>();
	fuseableSubscriber.onSubscribe(testQueue);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.SYNC))
			.as("fusion mode SYNC").isEqualTo(Fuseable.SYNC);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.ASYNC))
			.as("fusion mode ASYNC").isEqualTo(Fuseable.ASYNC);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.NONE))
			.as("fusion mode NONE").isEqualTo(Fuseable.NONE);
}
 
Example #3
Source File: KafkaProducerMetricsBinder.java    From summerframework with Apache License 2.0 6 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);
    }

    String nodeId = name.getKeyProperty("node-id");
    if (nodeId != null) {
        tags = Tags.concat(tags, "node-id", nodeId);
    }
    return tags;
}
 
Example #4
Source File: CountedThreadFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Wraps a {@link ThreadFactory} with an explicit name and records the number of created, running
 * and terminated threads.
 *
 * @param delegate {@link ThreadFactory} to wrap.
 * @param registry {@link MeterRegistry} that will contain the metrics.
 * @param name name for this delegate.
 * @param tags tags that can provide additional context.
 */
public CountedThreadFactory(
    ThreadFactory delegate, MeterRegistry registry, String name, Iterable<Tag> tags) {
  this.delegate = delegate;
  this.created =
      Counter.builder("thread.factory.created")
          .tags(Tags.concat(tags, "name", name))
          .description(
              "The approximate number of threads which were created with a thread factory")
          .baseUnit(BaseUnits.THREADS)
          .register(registry);
  this.terminated =
      Counter.builder("thread.factory.terminated")
          .tags(Tags.concat(tags, "name", name))
          .description("The approximate number of threads which have finished execution")
          .baseUnit(BaseUnits.THREADS)
          .register(registry);
  Gauge.builder("thread.factory.running", running, AtomicInteger::get)
      .tags(Tags.concat(tags, "name", name))
      .description(
          "The approximate number of threads which have started to execute, but have not terminated")
      .baseUnit(BaseUnits.THREADS)
      .register(registry);
}
 
Example #5
Source File: RqueueMetricsTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
private void verifyCounterRegisterMethodIsCalled(Tags tags) throws IllegalAccessException {
  MeterRegistry meterRegistry = new SimpleMeterRegistry();
  metricsProperties.setMetricTags(tags);
  RqueueMetrics metrics = rqueueMetrics(meterRegistry, metricsProperties);
  metrics.onApplicationEvent(new RqueueBootstrapEvent("Test", true));
  verify(queueCounter, times(1))
      .registerQueue(
          metricsProperties,
          Tags.concat(tags, "queue", simpleQueue),
          meterRegistry,
          simpleQueueDetail);
  verify(queueCounter, times(1))
      .registerQueue(
          metricsProperties,
          Tags.concat(tags, "queue", delayedQueue),
          meterRegistry,
          delayedQueueDetail);
  verify(queueCounter, times(2)).registerQueue(any(), any(), any(), any(QueueDetail.class));
}
 
Example #6
Source File: FluxMetricsFuseableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void requestFusionDelegates() {
	AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create();
	FluxMetricsFuseable.MetricsFuseableSubscriber<Integer> fuseableSubscriber =
			new FluxMetricsFuseable.MetricsFuseableSubscriber<>(testSubscriber,
					registry, Clock.SYSTEM, "foo", Tags.empty());

	Fuseable.QueueSubscription<Integer> testQueue = new FluxPeekFuseableTest.AssertQueueSubscription<>();
	fuseableSubscriber.onSubscribe(testQueue);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.SYNC))
			.as("fusion mode SYNC").isEqualTo(Fuseable.SYNC);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.ASYNC))
			.as("fusion mode ASYNC").isEqualTo(Fuseable.ASYNC);

	assertThat(fuseableSubscriber.requestFusion(Fuseable.NONE))
			.as("fusion mode NONE").isEqualTo(Fuseable.NONE);
}
 
Example #7
Source File: CounterSample.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    Counter counter = registry.counter("counter", "method", "actual");

    AtomicInteger n = new AtomicInteger(0);
    registry.more().counter("counter", Tags.of("method", "function"), n);

    RandomEngine r = new MersenneTwister64(0);
    Normal dist = new Normal(0, 1, r);

    Flux.interval(Duration.ofMillis(10))
            .doOnEach(d -> {
                if (dist.nextDouble() + 0.1 > 0) {
                    counter.increment();
                    n.incrementAndGet();
                }
            })
            .blockLast();
}
 
Example #8
Source File: MonoMetricsTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void usesTags() {
	Mono<Integer> source = Mono.just(1)
	                           .tag("tag1", "A")
	                           .name("usesTags")
	                           .tag("tag2", "foo")
	                           .hide();
	new MonoMetrics<>(source, registry)
			.block();

	Timer meter = registry
			.find(METER_FLOW_DURATION)
			.tags(Tags.of(TAG_ON_COMPLETE))
			.tag(TAG_SEQUENCE_NAME, "usesTags")
			.tag("tag1", "A")
			.tag("tag2", "foo")
			.timer();

	assertThat(meter).isNotNull();
	assertThat(meter.count()).isEqualTo(1L);
}
 
Example #9
Source File: MicrometerBasedMetricsTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that when reporting a downstream message no tags for
 * {@link QoS#UNKNOWN} nor {@link TtdStatus#NONE} are included.
 *
 * @param registry The registry that the tests should be run against.
 */
@ParameterizedTest
@MethodSource("registries")
public void testReportTelemetryWithUnknownTagValues(final MeterRegistry registry) {

    final MicrometerBasedMetrics metrics = new MicrometerBasedMetrics(registry, mock(Vertx.class));

    metrics.reportTelemetry(
            MetricsTags.EndpointType.TELEMETRY,
            "tenant",
            TenantObject.from("tenant", true),
            MetricsTags.ProcessingOutcome.FORWARDED,
            MetricsTags.QoS.UNKNOWN,
            1024,
            MetricsTags.TtdStatus.NONE,
            metrics.startTimer());

    final Tags expectedTags = Tags.of(MetricsTags.EndpointType.TELEMETRY.asTag())
            .and(MetricsTags.getTenantTag("tenant"))
            .and(MetricsTags.ProcessingOutcome.FORWARDED.asTag())
            .and(MetricsTags.QoS.UNKNOWN.asTag())
            .and(MetricsTags.TtdStatus.NONE.asTag());

    assertNotNull(registry.find(MicrometerBasedMetrics.METER_MESSAGES_RECEIVED).tags(expectedTags).timer());
}
 
Example #10
Source File: HttpMetricsTagConfiguration.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Bean
OncePerRequestFilter extractCountry() {
    return new OncePerRequestFilter() {
        private final ObjectMapper mapper = new ObjectMapper();

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain) throws ServletException, IOException {
            ContentCachingResponseWrapper cached = new ContentCachingResponseWrapper(response);
            filterChain.doFilter(request, cached);

            Object path = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
            if (path.equals("/api/person/{id}")) {
                // Prometheus requires the same tags on all `http.server.requests`. So we'll need to add
                // a `@Timed("person.requests") to the /api/person/{id} endpoint so it has a different name.
                Person person = mapper.readValue(cached.getContentAsByteArray(), Person.class);
                responseTags.put(response, Tags.of("country", person.getCountry()));
            }

            cached.copyBodyToResponse();
        }
    };
}
 
Example #11
Source File: SkywalkingMeterRegistryTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunctionTimer() {
    final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
    final FunctionTimerBean task = new FunctionTimerBean(1, 200);
    registry.more().timer("test_function_timer", Tags.of("skywalking", "test"), task,
        FunctionTimerBean::getCount, FunctionTimerBean::getTotalTime, TimeUnit.MILLISECONDS);
    final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));

    // Check is has appoint meter
    Assert.assertEquals(2, meterMap.size());
    Gauge countGauge = null;
    Gauge sumGauge = null;
    for (BaseMeter meter : meterMap.values()) {
        if (meter.getName().endsWith("count")) {
            countGauge = (Gauge) meter;
        } else if (meter.getName().endsWith("sum")) {
            sumGauge = (Gauge) meter;
        }
    }

    // Check data
    assertGauge(countGauge, "test_function_timer_count", tags, 1);
    assertGauge(sumGauge, "test_function_timer_sum", tags, 200);
}
 
Example #12
Source File: OkHttpMetricsEventListener.java    From micrometer with Apache License 2.0 6 votes vote down vote up
void time(CallState state) {
    Request request = state.request;
    boolean requestAvailable = request != null;

    Iterable<Tag> tags = Tags.of(
                    "method", requestAvailable ? request.method() : TAG_VALUE_UNKNOWN,
                    "uri", getUriTag(state, request),
                    "status", getStatusMessage(state.response, state.exception)
            )
            .and(extraTags)
            .and(stream(contextSpecificTags.spliterator(), false)
                    .map(contextTag -> contextTag.apply(request, state.response))
                    .collect(toList()))
            .and(getRequestTags(request))
            .and(generateTagsForRoute(request));

    if (includeHostTag) {
        tags = Tags.of(tags).and("host", requestAvailable ? request.url().host() : TAG_VALUE_UNKNOWN);
    }

    Timer.builder(this.requestsMetricName)
            .tags(tags)
            .description("Timer of OkHttp operation")
            .register(registry)
            .record(registry.config().clock().monotonicTime() - state.startTime, TimeUnit.NANOSECONDS);
}
 
Example #13
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 #14
Source File: CaffeineCacheMetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void reportExpectedGeneralMetrics() {
    MeterRegistry registry = new SimpleMeterRegistry();
    metrics.bindTo(registry);

    verifyCommonCacheMetrics(registry, metrics);

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

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

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

    FunctionCounter failedLoad = fetch(registry, "cache.load", Tags.of("result", "failure")).functionCounter();
    assertThat(failedLoad.count()).isEqualTo(stats.loadFailureCount());
}
 
Example #15
Source File: DatadogMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void postMetricDescriptionMetadataWhenDescriptionIsEnabledButNull() {
    DatadogConfig config = new DatadogConfig() {

        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public String apiKey() {
            return "fake";
        }
    };

    HttpSender httpSender = mock(HttpSender.class);
    DatadogMeterRegistry registry = DatadogMeterRegistry.builder(config).httpClient(httpSender).build();
    Meter.Id id = new Meter.Id("my.meter", Tags.empty(), null, null, Meter.Type.COUNTER);
    registry.postMetricDescriptionMetadata("my.meter", new DatadogMetricMetadata(id, true));
    verifyNoInteractions(httpSender);
}
 
Example #16
Source File: HazelcastCacheMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void doNotReportMissCountSinceNotImplemented() {
    MeterRegistry registry = new SimpleMeterRegistry();
    HazelcastCacheMetrics.monitor(registry, cache, expectedTag);

    assertThat(registry.find("cache.gets").tags(Tags.of("result", "miss")).functionCounter()).isNull();
}
 
Example #17
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 #18
Source File: FluxMetrics.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
MetricsSubscriber(CoreSubscriber<? super T> actual,
		MeterRegistry registry,
		Clock clock,
		String sequenceName,
		Tags commonTags) {
	this.actual = actual;
	this.clock = clock;
	this.commonTags = commonTags;
	this.registry = registry;


	this.onNextIntervalTimer = Timer.builder(METER_ON_NEXT_DELAY)
	                                .tags(commonTags)
	                                .description(
			                                "Measures delays between onNext signals (or between onSubscribe and first onNext)")
	                                .register(registry);

	if (!REACTOR_DEFAULT_NAME.equals(sequenceName)) {
		this.requestedCounter = DistributionSummary.builder(METER_REQUESTED)
		                                           .tags(commonTags)
		                                           .description(
				                                           "Counts the amount requested to a named Flux by all subscribers, until at least one requests an unbounded amount")
		                                           .baseUnit("requested amount")
		                                           .register(registry);
	}
	else {
		requestedCounter = null;
	}
}
 
Example #19
Source File: MicrometerBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportCommand(
        final Direction direction,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final int payloadSize,
        final Sample timer) {

    Objects.requireNonNull(direction);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(outcome);
    Objects.requireNonNull(timer);

    if (payloadSize < 0) {
        throw new IllegalArgumentException("payload size must not be negative");
    }

    final Tags tags = Tags.of(direction.asTag())
            .and(MetricsTags.getTenantTag(tenantId))
            .and(outcome.asTag());

    timer.stop(this.registry.timer(METER_COMMANDS_RECEIVED, tags));

    // record payload size
    DistributionSummary.builder(METER_COMMANDS_PAYLOAD)
        .baseUnit("bytes")
        .minimumExpectedValue(0L)
        .tags(tags)
        .register(this.registry)
        .record(ServiceBaseUtils.calculatePayloadSize(payloadSize, tenantObject));

    updateLastSeenTimestamp(tenantId);
}
 
Example #20
Source File: JvmThreadMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount)
            .tags(tags)
            .description("The peak live thread count since the Java virtual machine started or peak was reset")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount)
            .tags(tags)
            .description("The current number of live daemon threads")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount)
            .tags(tags)
            .description("The current number of live threads including both daemon and non-daemon threads")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    try {
        threadBean.getAllThreadIds();
        for (Thread.State state : Thread.State.values()) {
            Gauge.builder("jvm.threads.states", threadBean, (bean) -> getThreadStateCount(bean, state))
                    .tags(Tags.concat(tags, "state", getStateTagValue(state)))
                    .description("The current number of threads having " + state + " state")
                    .baseUnit(BaseUnits.THREADS)
                    .register(registry);
        }
    } catch (Error error) {
        // An error will be thrown for unsupported operations
        // e.g. SubstrateVM does not support getAllThreadIds
    }
}
 
Example #21
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 #22
Source File: DiskSpaceMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void diskSpaceMetricsWithTags() {
    new DiskSpaceMetrics(new File(System.getProperty("user.dir")), Tags.of("key1", "value1")).bindTo(registry);

    assertThat(registry.get("disk.free").tags("key1", "value1").gauge().value()).isNotNaN().isGreaterThan(0);
    assertThat(registry.get("disk.total").tags("key1", "value1").gauge().value()).isNotNaN().isGreaterThan(0);
}
 
Example #23
Source File: OkHttpConnectionPoolMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void maxIfNotGiven() {
    OkHttpConnectionPoolMetrics instance = new OkHttpConnectionPoolMetrics(connectionPool, "huge.pool", Tags.of("foo", "bar"), null);
    instance.bindTo(registry);
    assertThrows(MeterNotFoundException.class, () -> registry.get("huge.pool.connection.limit")
            .tags(Tags.of("foo", "bar"))
            .gauge());
}
 
Example #24
Source File: CommonMetricsFilterTest.java    From foremast with Apache License 2.0 5 votes vote down vote up
@Test
public void tagRules() {
    K8sMetricsProperties k8sMetricsProperties = new K8sMetricsProperties();
    k8sMetricsProperties.setEnableCommonMetricsFilter(true);
    k8sMetricsProperties.setCommonMetricsTagRules("myTag:true");

    MetricsProperties metricsProperties = new MetricsProperties();
    CommonMetricsFilter filter = new CommonMetricsFilter(k8sMetricsProperties, metricsProperties);
    MeterFilterReply reply = filter.accept(new Meter.Id("prefix.abc", Tags.of("myTag", "true"), "", "", Meter.Type.COUNTER));
    assertEquals(reply, MeterFilterReply.ACCEPT);

    reply = filter.accept(new Meter.Id("prefix.abc", Tags.of("myTag", "false"), "", "", Meter.Type.COUNTER));
    assertEquals(reply, MeterFilterReply.DENY);
}
 
Example #25
Source File: GatewayRSocketTests.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Override
protected PendingRequestRSocket constructPendingRSocket(
		GatewayExchange exchange) {
	Function<RoutingTable.RegisteredEvent, Mono<Route>> routeFinder = registeredEvent -> getRouteMono(
			registeredEvent, exchange);
	return new PendingRequestRSocket(metadataExtractor, routeFinder,
			tagsMetadata -> {
				Tags tags = exchange.getTags().and("responder.id",
						tagsMetadata.getRouteId());
				exchange.setTags(tags);
			}, processor);
}
 
Example #26
Source File: GatewayRSocket.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<Payload> requestStream(Payload payload) {
	GatewayExchange exchange = createExchange(REQUEST_STREAM, payload);
	return findRSocketOrCreatePending(exchange).flatMapMany(rSockets -> {
		retain(payload, rSockets);
		List<Flux<Payload>> results = rSockets.stream()
				.map(rSocket -> rSocket.requestStream(payload))
				.collect(Collectors.toList());
		return Flux.merge(results);
	})
			// S N E F
			.doOnNext(s -> count(exchange, "payload"))
			.doOnError(t -> count(exchange, "error"))
			.doFinally(s -> count(exchange, Tags.empty()));
}
 
Example #27
Source File: MicrometerHttpRequestExecutor.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
    Timer.Sample timerSample = Timer.start(registry);

    Tag method = Tag.of("method", request.getRequestLine().getMethod());
    Tag uri = Tag.of("uri", uriMapper.apply(request));
    Tag status = STATUS_UNKNOWN;

    Tags routeTags = exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty();

    try {
        HttpResponse response = super.execute(request, conn, context);
        status = response != null ? Tag.of("status", Integer.toString(response.getStatusLine().getStatusCode())) : STATUS_CLIENT_ERROR;
        return response;
    } catch (IOException | HttpException | RuntimeException e) {
        status = STATUS_IO_ERROR;
        throw e;
    } finally {
        Iterable<Tag> tags = Tags.of(extraTags)
                .and(routeTags)
                .and(uri, method, status);

        timerSample.stop(Timer.builder(METER_NAME)
                .description("Duration of Apache HttpClient request execution")
                .tags(tags)
                .register(registry));
    }
}
 
Example #28
Source File: CountedRejectedExecutionHandler.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public CountedRejectedExecutionHandler(
    RejectedExecutionHandler delegate, MeterRegistry registry, String name, Iterable<Tag> tags) {
  this.delegate = delegate;
  this.counter =
      Counter.builder("executor.rejected")
          .tags(Tags.concat(tags, "name", name))
          .description("The number of tasks not accepted for execution")
          .baseUnit(BaseUnits.TASKS)
          .register(registry);
}
 
Example #29
Source File: AbstractGatewayRSocket.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
protected GatewayExchange createExchange(GatewayExchange.Type type, Payload payload) {
	GatewayExchange exchange = GatewayExchange.fromPayload(type, payload,
			metadataExtractor);
	Tags tags = getTags(exchange);
	exchange.setTags(tags);
	return exchange;
}
 
Example #30
Source File: DataSourcePoolMetrics.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DataSourcePoolMetrics( DataSource dataSource, DataSourcePoolMetadataProvider metadataProvider, String name,
    Iterable<Tag> tags )
{
    Assert.notNull( dataSource, "DataSource must not be null" );
    Assert.notNull( metadataProvider, "MetadataProvider must not be null" );
    this.dataSource = dataSource;
    this.metadataProvider = new CachingDataSourcePoolMetadataProvider( metadataProvider );
    this.tags = Tags.concat( tags, "name", name );
}