Java Code Examples for io.micrometer.core.instrument.Timer#Sample

The following examples show how to use io.micrometer.core.instrument.Timer#Sample . 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: GatewayRSocket.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Payload> requestResponse(Payload payload) {
	AtomicReference<Timer.Sample> timer = new AtomicReference<>();
	GatewayExchange exchange = createExchange(REQUEST_RESPONSE, payload);
	return findRSocketOrCreatePending(exchange).flatMap(rSockets -> {
		retain(payload, rSockets);
		List<Mono<Payload>> results = rSockets.stream()
				.map(rSocket -> rSocket.requestResponse(payload))
				.collect(Collectors.toList());

		return Flux.merge(results).next();
		// TODO: does this cancel the others?
	}).doOnSubscribe(s -> timer.set(Timer.start(meterRegistry)))
			.doOnError(t -> count(exchange, "error"))
			.doFinally(s -> timer.get().stop(meterRegistry
					.timer(getMetricName(exchange), exchange.getTags())));
}
 
Example 2
Source File: MolgenisTimedAspect.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Object timedProceed(ProceedingJoinPoint pjp, Timed timed) throws Throwable {
  if (timed.value().isEmpty()) {
    return pjp.proceed();
  }
  Timer.Sample sample = Timer.start(registry);
  try {
    return pjp.proceed();
  } finally {
    sample.stop(
        Timer.builder(timed.value())
            .description(timed.description().isEmpty() ? null : timed.description())
            .tags(timed.extraTags())
            .tags(tagsBasedOnJoinpoint.apply(pjp))
            .publishPercentileHistogram(timed.histogram())
            .publishPercentiles(timed.percentiles().length == 0 ? null : timed.percentiles())
            .register(registry));
  }
}
 
Example 3
Source File: AbstractOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Log the reconciliation outcome.
 */
private void handleResult(Reconciliation reconciliation, AsyncResult<Void> result, Timer.Sample reconciliationTimerSample) {
    if (result.succeeded()) {
        successfulReconciliationsCounter.increment();
        reconciliationTimerSample.stop(reconciliationsTimer);
        log.info("{}: reconciled", reconciliation);
    } else {
        Throwable cause = result.cause();
        if (cause instanceof InvalidConfigParameterException) {
            failedReconciliationsCounter.increment();
            reconciliationTimerSample.stop(reconciliationsTimer);
            log.warn("{}: Failed to reconcile {}", reconciliation, cause.getMessage());
        } else if (cause instanceof UnableToAcquireLockException) {
            lockedReconciliationsCounter.increment();
        } else  {
            failedReconciliationsCounter.increment();
            reconciliationTimerSample.stop(reconciliationsTimer);
            log.warn("{}: Failed to reconcile", reconciliation, cause);
        }
    }
}
 
Example 4
Source File: AbstractConnectOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
Future<Void> reconcileConnectorAndHandleResult(Reconciliation reconciliation, String host, KafkaConnectApi apiClient,
                                         boolean useResources, String connectorName, KafkaConnector connector) {
    Promise<Void> reconciliationResult = Promise.promise();

    connectorsReconciliationsCounter.increment();
    Timer.Sample connectorsReconciliationsTimerSample = Timer.start(metrics.meterRegistry());

    reconcileConnector(reconciliation, host, apiClient, useResources, connectorName, connector)
            .onComplete(result -> {
                connectorsReconciliationsTimerSample.stop(connectorsReconciliationsTimer);

                if (result.succeeded())    {
                    connectorsSuccessfulReconciliationsCounter.increment();
                    reconciliationResult.complete();
                } else {
                    connectorsFailedReconciliationsCounter.increment();
                    reconciliationResult.fail(result.cause());
                }
            });

    return reconciliationResult.future();
}
 
Example 5
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
    ContainerRequest containerRequest = event.getContainerRequest();
    Set<Timed> timedAnnotations;

    switch (event.getType()) {
        case ON_EXCEPTION:
            if (!(event.getException() instanceof NotFoundException)) {
                break;
            }
        case REQUEST_MATCHED:
            timedAnnotations = annotations(event);

            timedAnnotationsOnRequest.put(containerRequest, timedAnnotations);
            shortTaskSample.put(containerRequest, Timer.start(registry));

            List<LongTaskTimer.Sample> longTaskSamples = longTaskTimers(timedAnnotations, event).stream().map(LongTaskTimer::start).collect(Collectors.toList());
            if (!longTaskSamples.isEmpty()) {
                this.longTaskSamples.put(containerRequest, longTaskSamples);
            }
            break;
        case FINISHED:
            timedAnnotations = timedAnnotationsOnRequest.remove(containerRequest);
            Timer.Sample shortSample = shortTaskSample.remove(containerRequest);

            if (shortSample != null) {
                for (Timer timer : shortTimers(timedAnnotations, event)) {
                    shortSample.stop(timer);
                }
            }

            Collection<LongTaskTimer.Sample> longSamples = this.longTaskSamples.remove(containerRequest);
            if (longSamples != null) {
                for (LongTaskTimer.Sample longSample : longSamples) {
                    longSample.stop();
                }
            }
            break;
    }
}
 
Example 6
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("record with stateful Sample instance")
default void recordWithSample(MeterRegistry registry) {
    Timer timer = registry.timer("myTimer");
    Timer.Sample sample = Timer.start(registry);

    clock(registry).add(10, TimeUnit.NANOSECONDS);
    sample.stop(timer);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, timer.count()),
            () -> assertEquals(10, timer.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
Example 7
Source File: TimerBenchmark.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Benchmark
public int sumTimedWithSample() {
    Timer.Sample sample = Timer.start(registry);
    int sum = sum();
    sample.stop(timer);
    return sum;
}
 
Example 8
Source File: TimedCallable.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public V call() throws Exception {
    idleSample.stop(idleTimer);
    Timer.Sample executionSample = Timer.start(registry);
    try {
        return callable.call();
    } finally {
        executionSample.stop(executionTimer);
    }
}
 
Example 9
Source File: TimedRunnable.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    idleSample.stop(idleTimer);
    Timer.Sample executionSample = Timer.start(registry);
    try {
        command.run();
    } finally {
        executionSample.stop(executionTimer);
    }
}
 
Example 10
Source File: JettyConnectionMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(Connection connection) {
    Timer.Sample started = Timer.start(registry);
    synchronized (connectionSamplesLock) {
        connectionSamples.put(connection, started);
        maxConnections.record(connectionSamples.size());
    }
}
 
Example 11
Source File: JooqExecuteListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void stopTimerIfStillRunning(ExecuteContext ctx) {
    Iterable<Tag> queryTags = queryTagsSupplier.get();
    if (queryTags == null) return;

    Timer.Sample sample;
    synchronized (sampleLock) {
        sample = sampleByExecuteContext.remove(ctx);
    }
    if (sample == null) return;

    String exceptionName = "none";
    String exceptionSubclass = "none";

    Exception exception = ctx.exception();
    if (exception != null) {
        if (exception instanceof DataAccessException) {
            DataAccessException dae = (DataAccessException) exception;
            exceptionName = dae.sqlStateClass().name().toLowerCase().replace('_', ' ');
            exceptionSubclass = dae.sqlStateSubclass().name().toLowerCase().replace('_', ' ');
            if (exceptionSubclass.contains("no subclass")) {
                exceptionSubclass = "none";
            }
        } else {
            String simpleName = exception.getClass().getSimpleName();
            exceptionName = StringUtils.isNotBlank(simpleName) ? simpleName : exception.getClass().getName();
        }
    }

    //noinspection unchecked
    sample.stop(Timer.builder("jooq.query")
            .description("Execution time of a SQL query performed with JOOQ")
            .tags(queryTags)
            .tag("type", ctx.type().name().toLowerCase())
            .tag("exception", exceptionName)
            .tag("exception.subclass", exceptionSubclass)
            .tags(tags)
            .register(registry));
}
 
Example 12
Source File: ReactiveTimedAspect.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")
public Object timedMethod(ProceedingJoinPoint joinPoint) throws Throwable {

  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

  String className = methodSignature.getDeclaringType().getSimpleName();
  String methodName = methodSignature.getName();
  String metricName = String.format("%s.%s", className, methodName);

  Timer.Sample timer = Timer.start(registry);

  //@formatter:off
  return Try.of(joinPoint::proceed)
            .map(value ->
                Match(value).of(
                    Case($(instanceOf(Mono.class)),
                        m -> m.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(instanceOf(Flux.class)),
                        f -> f.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(), res -> {
                      stopTimer(className, methodName, metricName, timer);
                      return res;
                    })
                ))
            .get();
  //@formatter:on
}
 
Example 13
Source File: ReactiveTimedAspect.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")
public Object timedMethod(ProceedingJoinPoint joinPoint) throws Throwable {

  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

  String className = methodSignature.getDeclaringType().getSimpleName();
  String methodName = methodSignature.getName();
  String metricName = String.format("%s.%s", className, methodName);

  Timer.Sample timer = Timer.start(registry);

  //@formatter:off
  return Try.of(joinPoint::proceed)
            .map(value ->
                Match(value).of(
                    Case($(instanceOf(Mono.class)),
                        m -> m.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(instanceOf(Flux.class)),
                        f -> f.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(), res -> {
                      stopTimer(className, methodName, metricName, timer);
                      return res;
                    })
                ))
            .get();
  //@formatter:on
}
 
Example 14
Source File: FluxMetrics.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
static void recordOnError(Tags commonTags, MeterRegistry registry, Timer.Sample flowDuration, Throwable e) {
	Timer timer = Timer.builder(METER_FLOW_DURATION)
	                   .tags(commonTags.and(TAG_ON_ERROR))
	                   .tag(TAG_KEY_EXCEPTION,
			                   e.getClass()
			                    .getName())
	                   .description(
			                   "Times the duration elapsed between a subscription and the onError termination of the sequence, with the exception name as a tag.")
	                   .register(registry);

	flowDuration.stop(timer);
}
 
Example 15
Source File: AbstractBatchMetricsAspect.java    From spring-boot-starter-batch-web with Apache License 2.0 5 votes vote down vote up
protected Object profileMethod(ProceedingJoinPoint pjp) throws Throwable {
	Timer.Sample sample = Timer.start(meterRegistry);
	try {
		return pjp.proceed();
	} finally {
		sample.stop(meterRegistry.timer(MetricsListener.METRIC_NAME, Arrays.asList(//
				new ImmutableTag("context", getStepIdentifier()), //
				new ImmutableTag("method", ClassUtils.getShortName(pjp.getTarget().getClass()) + "."
						+ pjp.getSignature().getName()))));
	}
}
 
Example 16
Source File: JooqExecuteListener.java    From micrometer with Apache License 2.0 4 votes vote down vote up
private void startTimer(ExecuteContext ctx) {
    Timer.Sample started = Timer.start(registry);
    synchronized (sampleLock) {
        sampleByExecuteContext.put(ctx, started);
    }
}
 
Example 17
Source File: TimedAspect.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 4 votes vote down vote up
private void stopTimer(String className, String methodName, String metricName, Timer.Sample timer) {
  long elapsedTime = timer.stop(getTimer(className, methodName, metricName));
  long elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);

  LOGGER.debug("Execution of method : {} took : {} milliseconds", metricName, elapsedTimeInSeconds);
}
 
Example 18
Source File: AbstractOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Reconcile assembly resources in the given namespace having the given {@code name}.
 * Reconciliation works by getting the assembly resource (e.g. {@code KafkaUser})
 * in the given namespace with the given name and
 * comparing with the corresponding resource.
 * @param reconciliation The reconciliation.
 * @return A Future which is completed with the result of the reconciliation.
 */
@Override
public final Future<Void> reconcile(Reconciliation reconciliation) {
    String namespace = reconciliation.namespace();
    String name = reconciliation.name();

    reconciliationsCounter.increment();
    Timer.Sample reconciliationTimerSample = Timer.start(metrics.meterRegistry());

    Future<Void> handler = withLock(reconciliation, LOCK_TIMEOUT_MS, () -> {
        T cr = resourceOperator.get(namespace, name);
        if (cr != null) {
            validate(cr);
            log.info("{}: {} {} should be created or updated", reconciliation, kind, name);
            return createOrUpdate(reconciliation, cr).recover(createResult -> {
                log.error("{}: createOrUpdate failed", reconciliation, createResult);
                return Future.failedFuture(createResult);
            });
        } else {
            log.info("{}: {} {} should be deleted", reconciliation, kind, name);
            return delete(reconciliation).map(deleteResult -> {
                if (deleteResult) {
                    log.info("{}: {} {} deleted", reconciliation, kind, name);
                } else {
                    log.info("{}: Assembly {} should be deleted by garbage collection", reconciliation, name);
                }
                return (Void) null;
            }).recover(deleteResult -> {
                log.error("{}: Deletion of {} {} failed", reconciliation, kind, name, deleteResult);
                return Future.failedFuture(deleteResult);
            });
        }
    });

    Promise<Void> result = Promise.promise();
    handler.onComplete(reconcileResult -> {
        handleResult(reconciliation, reconcileResult, reconciliationTimerSample);
        result.handle(reconcileResult);
    });

    return result.future();
}
 
Example 19
Source File: ReactiveTimedAspect.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 4 votes vote down vote up
private void stopTimer(String className, String methodName, String metricName, Timer.Sample timer) {
  long elapsedTime = timer.stop(getTimer(className, methodName, metricName));
  long elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);

  LOGGER.debug("Execution of method : {} took : {} milliseconds", metricName, elapsedTimeInSeconds);
}
 
Example 20
Source File: ReactiveTimedAspect.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 4 votes vote down vote up
private void stopTimer(String className, String methodName, String metricName, Timer.Sample timer) {
  long elapsedTime = timer.stop(getTimer(className, methodName, metricName));
  long elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);

  LOGGER.debug("Execution of method : {} took : {} milliseconds", metricName, elapsedTimeInSeconds);
}