io.micrometer.core.instrument.Timer Java Examples

The following examples show how to use io.micrometer.core.instrument.Timer. 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: TimerTest.java    From micrometer with Apache License 2.0 8 votes vote down vote up
@DisplayName("autocloseable sample")
@ParameterizedTest(name = "when outcome is '{0}'")
@CsvSource({"success", "error"})
@Issue("#1425")
default void closeable(String outcome) {
    MeterRegistry registry = new SimpleMeterRegistry();

    try (Timer.ResourceSample sample = Timer.resource(registry, "requests")
            .description("This is an operation")
            .publishPercentileHistogram()) {
        try {
            if (outcome.equals("error")) {
                throw new IllegalArgumentException("boom");
            }
            sample.tag("outcome", "success");
        } catch (Throwable t) {
            sample.tag("outcome", "error");
        }
    }

    assertThat(registry.get("requests").tag("outcome", outcome).timer().count())
            .isEqualTo(1);
}
 
Example #2
Source File: SkywalkingTimerTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTimer() {
    // Creating a simplify timer
    final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
    final Timer timer = registry.timer("test_simple_timer", "skywalking", "test");

    // Check Skywalking type
    Assert.assertTrue(timer instanceof SkywalkingTimer);
    final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));

    // Multiple record data
    timer.record(10, TimeUnit.MILLISECONDS);
    timer.record(20, TimeUnit.MILLISECONDS);
    timer.record(3, TimeUnit.MILLISECONDS);

    // Check micrometer data
    Assert.assertEquals(3, timer.count());
    Assert.assertEquals(33d, timer.totalTime(TimeUnit.MILLISECONDS), 0.0);
    Assert.assertEquals(20d, timer.max(TimeUnit.MILLISECONDS), 0.0);

    // Check Skywalking data
    assertCounter(Whitebox.getInternalState(timer, "counter"), "test_simple_timer_count", tags, 3d);
    assertCounter(Whitebox.getInternalState(timer, "sum"), "test_simple_timer_sum", tags, 33d);
    assertGauge(Whitebox.getInternalState(timer, "max"), "test_simple_timer_max", tags, 20d);
    assertHistogramNull(Whitebox.getInternalState(timer, "histogram"));
}
 
Example #3
Source File: OnrampController.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Sends a given array of messages to a road")
@ApiResponses({
    @ApiResponse(code = 200, message = "Messages have been sent successfully.", response = StandardResponse.class),
    @ApiResponse(code = 400, message = "Bad Request.", response = StandardResponse.class),
    @ApiResponse(code = 404, message = "Road not found.", response = StandardResponse.class),
    @ApiResponse(code = 422, message = "Road not enabled.", response = StandardResponse.class) })
@PreAuthorize("@onrampAuthorisation.isAuthorised(authentication,#roadName)")
@PostMapping(path = "/roads/{roadName}/messages")
public Iterable<StandardResponse> produce(@PathVariable String roadName, @RequestBody ArrayNode json)
  throws UnknownRoadException, InterruptedException {
  Timer.Sample sample = Timer.start(registry);
  DistributionSummary.builder("onramp.request").tag("road", roadName).register(registry).record(json.size());
  Onramp onramp = service.getOnramp(roadName).orElseThrow(() -> new UnknownRoadException(roadName));
  if (!onramp.isAvailable()) {
    throw new RoadUnavailableException(String.format("Road '%s' is disabled, could not send events.", roadName));
  }
  Iterable<StandardResponse> responses = sendMessages(onramp, json);
  sample.stop(registry.timer("onramp.request.timer", "road", roadName));
  return responses;
}
 
Example #4
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void configureHttp(ChannelPipeline p, @Nullable ProxiedAddresses proxiedAddresses) {
    final long idleTimeoutMillis = config.idleTimeoutMillis();
    final KeepAliveHandler keepAliveHandler;
    if (idleTimeoutMillis > 0) {
        final Timer keepAliveTimer = newKeepAliveTimer(H1C);
        keepAliveHandler = new Http1ServerKeepAliveHandler(
                p.channel(), keepAliveTimer, idleTimeoutMillis, config.maxConnectionAgeMillis());
    } else {
        keepAliveHandler = null;
    }
    final ServerHttp1ObjectEncoder responseEncoder = new ServerHttp1ObjectEncoder(
            p.channel(), H1C, keepAliveHandler,
            config.isDateHeaderEnabled(), config.isServerHeaderEnabled()
    );
    p.addLast(TrafficLoggingHandler.SERVER);
    p.addLast(new Http2PrefaceOrHttpHandler(responseEncoder));
    p.addLast(new HttpServerHandler(config, gracefulShutdownSupport, responseEncoder,
                                    H1C, proxiedAddresses));
}
 
Example #5
Source File: SpectatorTimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void timerMax() {
    AtlasConfig atlasConfig = new AtlasConfig() {
        @Override
        public String get(String k) {
            return null;
        }

        @Override
        public Duration lwcStep() {
            return step();
        }
    };
    AtlasMeterRegistry registry = new AtlasMeterRegistry(atlasConfig, new MockClock());
    Timer timer = registry.timer("timer");

    timer.record(1, TimeUnit.SECONDS);
    clock(registry).add(atlasConfig.step());
    assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);
}
 
Example #6
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public final NumericQuery count(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof Counter) {
                    return ((Counter) m).count();
                } else if (m instanceof Timer) {
                    return (double) ((Timer) m).count();
                } else if (m instanceof FunctionTimer) {
                    return ((FunctionTimer) m).count();
                } else if (m instanceof FunctionCounter) {
                    ((FunctionCounter) m).count();
                } else if (m instanceof LongTaskTimer) {
                    return (double) ((LongTaskTimer) m).activeTasks();
                }
                return Double.NaN;
            })
            .reduce(Double.NaN, SUM_OR_NAN)
    );
}
 
Example #7
Source File: HistogramGaugesTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void histogramsContainLongMaxValue() {
    MeterRegistry registry = new SimpleMeterRegistry();

    Timer timer = Timer.builder("my.timer")
            .serviceLevelObjectives(Duration.ofNanos(Long.MAX_VALUE))
            .register(registry);

    DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution")
            .serviceLevelObjectives(Double.POSITIVE_INFINITY)
            .register(registry);

    HistogramGauges distributionGauges = HistogramGauges.registerWithCommonFormat(distributionSummary, registry);

    HistogramGauges timerGauges = HistogramGauges.registerWithCommonFormat(timer, registry);

    assertThat(registry.get("my.distribution.histogram").tag("le", "+Inf").gauge()).isNotNull();
    assertThat(registry.get("my.timer.histogram").tag("le", "+Inf").gauge()).isNotNull();
}
 
Example #8
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimer_whenWrapTasks_thenTimeRecorded() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    Timer timer = registry.timer("app.event");
    timer.record(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep(15);
        } catch (InterruptedException ignored) {
        }
    });

    timer.record(30, TimeUnit.MILLISECONDS);

    assertTrue(2 == timer.count());
    
    assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isBetween(40.0, 55.0);
}
 
Example #9
Source File: KeepAliveHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
protected KeepAliveHandler(Channel channel, String name, Timer keepAliveTimer,
                           long idleTimeoutMillis, long pingIntervalMillis, long maxConnectionAgeMillis) {
    this.channel = channel;
    this.name = name;
    this.keepAliveTimer = keepAliveTimer;

    if (idleTimeoutMillis <= 0) {
        connectionIdleTimeNanos = 0;
    } else {
        connectionIdleTimeNanos = TimeUnit.MILLISECONDS.toNanos(idleTimeoutMillis);
    }

    if (pingIntervalMillis <= 0) {
        pingIdleTimeNanos = 0;
    } else {
        pingIdleTimeNanos = TimeUnit.MILLISECONDS.toNanos(pingIntervalMillis);
    }

    if (maxConnectionAgeMillis <= 0) {
        maxConnectionAgeNanos = 0;
    } else {
        maxConnectionAgeNanos = TimeUnit.MILLISECONDS.toNanos(maxConnectionAgeMillis);
    }
}
 
Example #10
Source File: MicrometerPluginTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldRecordErrorResponseMetric() {
    driver.addExpectation(onRequestTo("/bar").withMethod(POST),
            giveEmptyResponse().withStatus(503));

    unit.post(URI.create("/bar"))
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()))
            .exceptionally(e -> null)
            .join();

    @Nullable final Timer timer = search().timer();

    assertThat(timer, is(notNullValue()));
    assertThat(timer.getId().getTag("http.method"), is("POST"));
    assertThat(timer.getId().getTag("http.path"), is(""));
    assertThat(timer.getId().getTag("http.status_code"), is("503"));
    assertThat(timer.getId().getTag("peer.hostname"), is("localhost"));
    assertThat(timer.getId().getTag("error.kind"), is("none"));
    assertThat(timer.getId().getTag("client"), is("example"));
    assertThat(timer.getId().getTag("test"), is("true"));
    assertThat(timer.totalTime(NANOSECONDS), is(greaterThan(0.0)));
}
 
Example #11
Source File: TimersTest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAliasTimerLabel() {
  MeterRegistry registry = new SimpleMeterRegistry();
  BackendRegistries.registerMatchers(registry, ALL_LABELS, Collections.singletonList(new Match()
    .setLabel("address")
    .setType(MatchType.REGEX)
    .setValue("addr1")
    .setAlias("1")));
  Timers timers = new Timers("my_timer", "", registry, Label.EB_ADDRESS);
  timers.get("addr1").record(5, TimeUnit.MILLISECONDS);
  timers.get("addr1").record(8, TimeUnit.MILLISECONDS);
  timers.get("addr2").record(10, TimeUnit.MILLISECONDS);

  Timer t = registry.find("my_timer").tags("address", "1").timer();
  assertThat(t.count()).isEqualTo(2);
  assertThat(t.totalTime(TimeUnit.MILLISECONDS)).isEqualTo(13);
  t = registry.find("my_timer").tags("address", "addr1").timer();
  assertThat(t).isNull();
  t = registry.find("my_timer").tags("address", "addr2").timer();
  assertThat(t.count()).isEqualTo(1);
  assertThat(t.totalTime(TimeUnit.MILLISECONDS)).isEqualTo(10);
}
 
Example #12
Source File: WorkspaceStopTrackerMeterBinderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldCountSuccessfulStart() {
  // given
  workspaceStopTime.put("id1", System.currentTimeMillis() - 60 * 1000);
  // when
  eventService.publish(
      DtoFactory.newDto(WorkspaceStatusEvent.class)
          .withPrevStatus(WorkspaceStatus.STOPPING)
          .withStatus(WorkspaceStatus.STOPPED)
          .withWorkspaceId("id1"));

  // then

  Timer t = registry.find("che.workspace.stop.time").tag("result", "success").timer();
  Assert.assertEquals(t.count(), 1);
  Assert.assertTrue(t.totalTime(TimeUnit.MILLISECONDS) >= 60 * 1000);
}
 
Example #13
Source File: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 6 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) {
        Timer timer = Timer
            .builder("http.server.requests")
            // no way to access the exception
            .tag("exception", "")
            .tag("outcome", computeOutcome(responseContext))
            .tag("method", getMethod(requestContext))
            .tag("status", getStatus(responseContext))
            .tag("uri", getUri())
            .publishPercentileHistogram()
            .maximumExpectedValue(Duration.ofSeconds(10))
            .register(registry);
        sample.stop(timer);
    }
}
 
Example #14
Source File: MetricUtils.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Creates a new timer builder for the given method.
 *
 * @param method The method the timer will be created for.
 * @param name The name of the timer to use.
 * @param description The description of the timer to use.
 * @return The newly created timer builder.
 */
public static Timer.Builder prepareTimerFor(final MethodDescriptor<?, ?> method,
        final String name, final String description) {
    return Timer.builder(name)
            .description(description)
            .tag(TAG_SERVICE_NAME, extractServiceName(method))
            .tag(TAG_METHOD_NAME, extractMethodName(method))
            .tag(TAG_METHOD_TYPE, method.getType().name());
}
 
Example #15
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public final NumericQuery max(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof DistributionSummary) {
                    return ((DistributionSummary) m).max();
                } else if (m instanceof Timer) {
                    return ((Timer) m).max(TimeUnit.NANOSECONDS);
                } else if (m instanceof LongTaskTimer) {
                    return ((LongTaskTimer) m).max(TimeUnit.NANOSECONDS);
                }
                return Double.NaN;
            })
            .reduce(Double.NaN, MAX_OR_NAN)
    );
}
 
Example #16
Source File: JHipsterMetricsEndpoint.java    From jhipster with Apache License 2.0 5 votes vote down vote up
private Map<String, Map> httpRequestsMetrics() {
    Set<String> statusCode = new HashSet<>();
    Collection<Timer> timers = this.meterRegistry.find("http.server.requests").timers();

    timers.forEach(timer -> statusCode.add(timer.getId().getTag("status")));

    Map<String, Map> resultsHttp = new HashMap<>();
    Map<String, Map<String, Number>> resultsHttpPerCode = new HashMap<>();

    statusCode.forEach(code -> {
        Map<String, Number> resultsPerCode = new HashMap<>();

        Collection<Timer> httpTimersStream = this.meterRegistry.find("http.server.requests").tag("status", code).timers();
        long count = httpTimersStream.stream().map(Timer::count).reduce((x, y) -> x + y).orElse(0L);
        double max = httpTimersStream.stream().map(x -> x.max(TimeUnit.MILLISECONDS)).reduce((x, y) -> x > y ? x : y).orElse((double) 0);
        double totalTime = httpTimersStream.stream().map(x -> x.totalTime(TimeUnit.MILLISECONDS)).reduce((x, y) -> (x + y)).orElse((double) 0);

        resultsPerCode.put("count", count);
        resultsPerCode.put("max", max);
        resultsPerCode.put("mean", count != 0 ? totalTime / count : 0);

        resultsHttpPerCode.put(code, resultsPerCode);
    });

    resultsHttp.put("percode", resultsHttpPerCode);

    timers = this.meterRegistry.find("http.server.requests").timers();
    long countAllrequests = timers.stream().map(Timer::count).reduce((x, y) -> x + y).orElse(0L);
    Map<String, Number> resultsHTTPAll = new HashMap<>();
    resultsHTTPAll.put("count", countAllrequests);

    resultsHttp.put("all", resultsHTTPAll);

    return resultsHttp;
}
 
Example #17
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 #18
Source File: WorkspaceStopTrackerMeterBinder.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {

  stopTimer =
      Timer.builder(workspaceMetric("stop.time"))
          .description("The time of workspace stop")
          .tags(withStandardTags("result", "success"))
          .register(registry);

  // only subscribe to the event once we have the counters ready
  eventService.subscribe(this::handleWorkspaceStatusChange, WorkspaceStatusEvent.class);
}
 
Example #19
Source File: MetricCollectingClientCall.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Creates a new delegating ClientCall that will wrap the given client call to collect metrics.
 *
 * @param delegate The original call to wrap.
 * @param registry The registry to save the metrics to.
 * @param requestCounter The counter for outgoing requests.
 * @param responseCounter The counter for incoming responses.
 * @param timerFunction A function that will return a timer for a given status code.
 */
public MetricCollectingClientCall(final ClientCall<Q, A> delegate, final MeterRegistry registry,
        final Counter requestCounter, final Counter responseCounter,
        final Function<Code, Timer> timerFunction) {
    super(delegate);
    this.registry = registry;
    this.requestCounter = requestCounter;
    this.responseCounter = responseCounter;
    this.timerFunction = timerFunction;
}
 
Example #20
Source File: MetricsSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
MetricsSubscriber(
    CoreSubscriber<? super T> actual,
    Counter next,
    Counter complete,
    Counter error,
    Counter cancelled,
    Timer timer) {
  this.actual = actual;
  this.next = next;
  this.complete = complete;
  this.error = error;
  this.cancelled = cancelled;
  this.timer = timer;
}
 
Example #21
Source File: Http2ServerConnectionHandlerBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
Http2ServerConnectionHandlerBuilder(Channel ch, ServerConfig config, Timer keepAliveTimer,
                                    GracefulShutdownSupport gracefulShutdownSupport, String scheme) {
    super(ch);
    this.config = config;
    this.keepAliveTimer = keepAliveTimer;
    this.gracefulShutdownSupport = gracefulShutdownSupport;
    this.scheme = scheme;
}
 
Example #22
Source File: Timers.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public Timer get(String... values) {
  // Get or create the Timer
  return Timer.builder(name)
    .description(description)
    .tags(Labels.toTags(keys, values))
    .register(registry);
}
 
Example #23
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void customTimerExample() {
  MeterRegistry registry = BackendRegistries.getDefaultNow();
  Timer timer = Timer
    .builder("my.timer")
    .description("a description of what this timer does")
    .register(registry);

  vertx.setPeriodic(1000, l -> {
    timer.record(() -> {
      // Running here some operation to monitor
    });
  });
}
 
Example #24
Source File: WebMvcMetricsFilter.java    From foremast with Apache License 2.0 5 votes vote down vote up
TimingSampleContext(HttpServletRequest request, Object handlerObject) {
    timedAnnotations = annotations(handlerObject);
    timerSample = Timer.start(registry);
    longTaskTimerSamples = timedAnnotations.stream()
        .filter(Timed::longTask)
        .map(t -> LongTaskTimer.builder(t)
            .tags(tagsProvider.httpLongRequestTags(request, handlerObject))
            .register(registry)
            .start())
        .collect(Collectors.toList());
}
 
Example #25
Source File: MicrometerChannelMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
public MicrometerChannelMetricsRecorder(String name, String protocol) {
	this.dataReceivedBuilder =
			DistributionSummary.builder(name + DATA_RECEIVED)
			                   .baseUnit("bytes")
			                   .description("Amount of the data received, in bytes")
			                   .tag(URI, protocol);

	this.dataSentBuilder =
			DistributionSummary.builder(name + DATA_SENT)
			                   .baseUnit("bytes")
			                   .description("Amount of the data sent, in bytes")
			                   .tag(URI, protocol);

	this.errorCountBuilder =
			Counter.builder(name + ERRORS)
			       .description("Number of errors that occurred")
			       .tag(URI, protocol);

	this.connectTimeBuilder =
			Timer.builder(name + CONNECT_TIME)
			     .description("Time spent for connecting to the remote address");

	this.tlsHandshakeTimeBuilder =
			Timer.builder(name + TLS_HANDSHAKE_TIME)
			     .description("Time spent for TLS handshake");

	this.addressResolverTimeBuilder =
			Timer.builder(name + ADDRESS_RESOLVER)
			     .description("Time spent for resolving the address");
}
 
Example #26
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Test
default void percentiles(MeterRegistry registry) {
    Timer t = Timer.builder("my.timer")
            .publishPercentiles(1)
            .register(registry);

    t.record(1, TimeUnit.MILLISECONDS);
    assertThat(t.percentile(1, TimeUnit.MILLISECONDS)).isEqualTo(1, Offset.offset(0.3));
    assertThat(t.percentile(0.5, TimeUnit.MILLISECONDS)).isNaN();
}
 
Example #27
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Stream<MetricDatum> timerData(Timer timer) {
    Stream.Builder<MetricDatum> metrics = Stream.builder();
    metrics.add(metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit())));
    long count = timer.count();
    metrics.add(metricDatum(timer.getId(), "count", StandardUnit.COUNT, count));
    if (count > 0) {
        metrics.add(metricDatum(timer.getId(), "avg", getBaseTimeUnit().name(), timer.mean(getBaseTimeUnit())));
        metrics.add(metricDatum(timer.getId(), "max", getBaseTimeUnit().name(), timer.max(getBaseTimeUnit())));
    }
    return metrics.build();
}
 
Example #28
Source File: MetricCollectingServerInterceptor.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
protected Function<Code, Timer> newTimerFunction(final MethodDescriptor<?, ?> method) {
    return asTimerFunction(() -> this.timerCustomizer.apply(
            prepareTimerFor(method,
                    METRIC_NAME_SERVER_PROCESSING_DURATION,
                    "The total time taken for the server to complete the call")));
}
 
Example #29
Source File: MicrometerHttpClientMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void recordResponseTime(SocketAddress remoteAddress, String uri, String method, String status, Duration time) {
	String address = Metrics.formatSocketAddress(remoteAddress);
	Timer responseTime = responseTimeCache.computeIfAbsent(new MeterKey(uri, address, method, status),
			key -> filter(responseTimeBuilder.tags(REMOTE_ADDRESS, address, URI, uri, METHOD, method, STATUS, status)
			                                 .register(REGISTRY)));
	if (responseTime != null) {
		responseTime.record(time);
	}
}
 
Example #30
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);
    }
}