/** * Returns a map of all the timers in the registry and their names. * * @return all the timers in the registry */ public SortedMap<String, Timer> getTimers() { return getTimers(MetricFilter.ALL); }
private Timer registerHdrTimer(MetricRegistry metricRegistry, final String metricName) { Timer timer; try { timer = metricRegistry.register(metricName, new HdrTimer(1, MINUTES, 1)); } catch (IllegalArgumentException e) { final SortedMap<String, Timer> timers = metricRegistry.getTimers((name, metric) -> metricName.equals(name)); timer = Iterables.getOnlyElement(timers.values()); } return timer; }
/** * Get an existing timer or create a new one if the requested one does not yet exist. Creation * is synchronized to assure that only one instance of the counter is created. * @param name timer name * @return new Timer, or existing one if it already exists, null if the metrics have not been * initialized. */ public static Timer getOrCreateTimer(String name) { if (self == null) return null; Map<String, Timer> timers = self.registry.getTimers(); Timer timer = timers.get(name); if (timer != null) return timer; synchronized (Metrics.class) { timers = self.registry.getTimers(); timer = timers.get(name); if (timer != null) return timer; return self.registry.timer(name); } }
private static List<Metric> allMetrics(MetricsSystem.InstanceType instanceType) { List<Metric> metrics = new ArrayList<>(); for (Entry<String, Gauge> entry : METRIC_REGISTRY.getGauges().entrySet()) { if (entry.getKey().startsWith(instanceType.toString())) { Object value = entry.getValue().getValue(); if (!(value instanceof Number)) { LOG.warn( "The value of metric {} of type {} is not sent to metrics master," + " only metrics value of number can be collected", entry.getKey(), entry.getValue().getClass().getSimpleName()); continue; } metrics.add(Metric.from(entry.getKey(), ((Number) value).longValue())); } } for (Entry<String, Counter> entry : METRIC_REGISTRY.getCounters().entrySet()) { metrics.add(Metric.from(entry.getKey(), entry.getValue().getCount())); } for (Entry<String, Meter> entry : METRIC_REGISTRY.getMeters().entrySet()) { // TODO(yupeng): From Meter's implementation, getOneMinuteRate can only report at rate of at // least seconds. if the client's duration is too short (i.e. < 1s), then getOneMinuteRate // would return 0 metrics.add(Metric.from(entry.getKey(), entry.getValue().getOneMinuteRate())); } for (Entry<String, Timer> entry : METRIC_REGISTRY.getTimers().entrySet()) { metrics.add(Metric.from(entry.getKey(), entry.getValue().getCount())); } return metrics; }
private static void assertTimer(String property, int expectedCount) { assertSummary(dropwizardRegistry.getTimers(), property, expectedCount); }
/** * Register Dropwizard health checks. * * @param pool the pool to register health checks for * @param hikariConfig the pool configuration * @param registry the HealthCheckRegistry into which checks will be registered */ public static void registerHealthChecks(final HikariPool pool, final HikariConfig hikariConfig, final HealthCheckRegistry registry) { final Properties healthCheckProperties = hikariConfig.getHealthCheckProperties(); final MetricRegistry metricRegistry = (MetricRegistry) hikariConfig.getMetricRegistry(); final long checkTimeoutMs = Long.parseLong(healthCheckProperties.getProperty("connectivityCheckTimeoutMs", String.valueOf(hikariConfig.getConnectionTimeout()))); registry.register(MetricRegistry.name(hikariConfig.getPoolName(), "pool", "ConnectivityCheck"), new ConnectivityHealthCheck(pool, checkTimeoutMs)); final long expected99thPercentile = Long.parseLong(healthCheckProperties.getProperty("expected99thPercentileMs", "0")); if (metricRegistry != null && expected99thPercentile > 0) { SortedMap<String,Timer> timers = metricRegistry.getTimers((name, metric) -> name.equals(MetricRegistry.name(hikariConfig.getPoolName(), "pool", "Wait"))); if (!timers.isEmpty()) { final Timer timer = timers.entrySet().iterator().next().getValue(); registry.register(MetricRegistry.name(hikariConfig.getPoolName(), "pool", "Connection99Percent"), new Connection99Percent(timer, expected99thPercentile)); } } }
public void reportRegistry(MetricRegistry registry) { Map<String, String> tags = Maps.newHashMap(); if (registry instanceof MetricContext) { tags = Maps.transformValues(((MetricContext) registry).getTagMap(), new Function<Object, String>() { @Override public String apply(Object input) { return input.toString(); } }); } report(registry.getGauges(this.filter), registry.getCounters(this.filter), registry.getHistograms(this.filter), registry.getMeters(this.filter), registry.getTimers(this.filter), tags); }
@Override public void report() { // we do not need to lock here, because the dropwizard registry is // internally a concurrent map @SuppressWarnings("rawtypes") final SortedMap<String, com.codahale.metrics.Gauge> gauges = registry.getGauges(); final SortedMap<String, com.codahale.metrics.Counter> counters = registry.getCounters(); final SortedMap<String, com.codahale.metrics.Histogram> histograms = registry.getHistograms(); final SortedMap<String, com.codahale.metrics.Meter> meters = registry.getMeters(); final SortedMap<String, com.codahale.metrics.Timer> timers = registry.getTimers(); this.reporter.report(gauges, counters, histograms, meters, timers); }
@VisibleForTesting void reportOnce() { // resolve the additional attributes once per report additionalAttributes = additionalAttributesSupplier.get(); if (additionalAttributes == null) { additionalAttributes = Collections.emptyMap(); } metricRegistry.getGauges().forEach(this::reportGauge); metricRegistry.getCounters().forEach(this::reportCounter); metricRegistry.getMeters().forEach(this::reportMeter); metricRegistry.getHistograms().forEach(this::reportHistogram); metricRegistry.getTimers().forEach(this::reportTimer); }
private ExtractorSummary toSummary(Extractor extractor) { final ExtractorMetrics metrics = ExtractorMetrics.create( MetricUtils.buildTimerMap(metricRegistry.getTimers().get(extractor.getCompleteTimerName())), MetricUtils.buildTimerMap(metricRegistry.getTimers().get(extractor.getConditionTimerName())), MetricUtils.buildTimerMap(metricRegistry.getTimers().get(extractor.getExecutionTimerName())), MetricUtils.buildTimerMap(metricRegistry.getTimers().get(extractor.getConverterTimerName())), metricRegistry.getCounters().get(extractor.getConditionHitsCounterName()).getCount(), metricRegistry.getCounters().get(extractor.getConditionMissesCounterName()).getCount()); return ExtractorSummary.create( extractor.getId(), extractor.getTitle(), extractor.getType().toString().toLowerCase(Locale.ENGLISH), extractor.getCursorStrategy().toString().toLowerCase(Locale.ENGLISH), extractor.getSourceField(), extractor.getTargetField(), extractor.getExtractorConfig(), extractor.getCreatorUserId(), extractor.converterConfigMap(), extractor.getConditionType().toString().toLowerCase(Locale.ENGLISH), extractor.getConditionValue(), extractor.getOrder(), extractor.getExceptionCount(), extractor.getConverterExceptionCount(), metrics); }
/** * Report the current values of all metrics in the registry. */ public void report() { synchronized (this) { report(registry.getGauges(filter), registry.getCounters(filter), registry.getHistograms(filter), registry.getMeters(filter), registry.getTimers(filter)); } }
metrics.put("meters", meters); Map<String, Object> timers = timers(registry.getTimers(filter), rateUnitLabel, rateFactor, durationUnitLabel, durationFactor, showSamples); if (timers.size() > 0) {
@Test public void testCompilationQueryMetric() { Timer timer = metricRegistry.getTimers().get(MetricsConstant.HS2_COMPILING_QUERIES); Counter counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_COMPILING_QUERIES); assertThat(timer, nullValue()); assertThat(counter, nullValue()); hook.beforeCompile(ctx); timer = metricRegistry.getTimers().get(MetricsConstant.HS2_COMPILING_QUERIES); counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_COMPILING_QUERIES); assertThat(timer.getCount(), equalTo(0l)); assertThat(counter.getCount(), equalTo(1l)); hook.afterCompile(ctx, false); timer = metricRegistry.getTimers().get(MetricsConstant.HS2_COMPILING_QUERIES); counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_COMPILING_QUERIES); assertThat(timer.getCount(), equalTo(1l)); assertThat(counter.getCount(), equalTo(0l)); }
@Test public void testExecutionQueryMetric() { Timer timer = metricRegistry.getTimers().get(MetricsConstant.HS2_EXECUTING_QUERIES); Counter counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_EXECUTING_QUERIES); assertThat(timer, nullValue()); assertThat(counter, nullValue()); hook.beforeExecution(ctx); timer = metricRegistry.getTimers().get(MetricsConstant.HS2_EXECUTING_QUERIES); counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_EXECUTING_QUERIES); assertThat(timer.getCount(), equalTo(0l)); assertThat(counter.getCount(), equalTo(1l)); hook.afterExecution(ctx, false); timer = metricRegistry.getTimers().get(MetricsConstant.HS2_EXECUTING_QUERIES); counter = metricRegistry.getCounters() .get(MetricsConstant.ACTIVE_CALLS + MetricsConstant.HS2_EXECUTING_QUERIES); assertThat(timer.getCount(), equalTo(1l)); assertThat(counter.getCount(), equalTo(0l)); }
@Test public void shouldDecorateCheckedSupplier() throws Throwable { // Given the HelloWorldService returns Hello world BDDMockito.given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world"); // And measure the call with a Timer CheckedFunction0<String> timedSupplier = Timer.decorateCheckedSupplier(timer, helloWorldService::returnHelloWorldWithException); String value = timedSupplier.apply(); assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(1); assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1); assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(0); assertThat(metricRegistry.getCounters().size()).isEqualTo(2); assertThat(metricRegistry.getTimers().size()).isEqualTo(1); assertThat(value).isEqualTo("Hello world"); // Then the helloWorldService should be invoked 1 time BDDMockito.then(helloWorldService).should(times(1)).returnHelloWorldWithException(); }
@Test public void testConcurrency() throws Exception { int threads = 4; ExecutorService executorService = Executors.newFixedThreadPool(threads); for (int i=0; i< threads; i++) { final int n = i; executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { MetricsFactory.getInstance().startStoredScope("method2"); MetricsFactory.getInstance().endStoredScope("method2"); return null; } }); } executorService.shutdown(); assertTrue(executorService.awaitTermination(10000, TimeUnit.MILLISECONDS)); Timer timer = metricRegistry.getTimers().get("method2"); Assert.assertEquals(4, timer.getCount()); Assert.assertTrue(timer.getMeanRate() > 0); }
@Test public void testScope() throws Exception { int runs = 5; for (int i = 0; i < runs; i++) { MetricsFactory.getInstance().startStoredScope("method1"); MetricsFactory.getInstance().endStoredScope("method1"); Timer timer = metricRegistry.getTimers().get("method1"); Assert.assertEquals(i + 1, timer.getCount()); } Timer timer = metricRegistry.getTimers().get("method1"); Assert.assertTrue(timer.getMeanRate() > 0); }
@Override public List<MetricFamilySamples> collect() { Map<String, MetricFamilySamples> mfSamplesMap = new HashMap<String, MetricFamilySamples>(); for (SortedMap.Entry<String, Gauge> entry : registry.getGauges().entrySet()) { addToMap(mfSamplesMap, fromGauge(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Counter> entry : registry.getCounters().entrySet()) { addToMap(mfSamplesMap, fromCounter(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Histogram> entry : registry.getHistograms().entrySet()) { addToMap(mfSamplesMap, fromHistogram(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Timer> entry : registry.getTimers().entrySet()) { addToMap(mfSamplesMap, fromTimer(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Meter> entry : registry.getMeters().entrySet()) { addToMap(mfSamplesMap, fromMeter(entry.getKey(), entry.getValue())); } return new ArrayList<MetricFamilySamples>(mfSamplesMap.values()); }
SortedMap<String, Timer> timers = metricRegistry.getTimers(); if (timers.size() > 0) { writeTimers(timers, writer);
@Test public void registersMetrics() throws InterruptedException { when(closeableLockService.lock(any(), any())).thenReturn(new LockRefreshToken(BigInteger.ONE, Long.MAX_VALUE)); snapshotTransactionManager.runTaskWithRetry(tx -> 42); MetricRegistry registry = snapshotTransactionManager.metricsManager.getRegistry(); assertThat(registry.getNames()) .contains(SETUP_TASK_METRIC_NAME) .contains(FINISH_TASK_METRIC_NAME); assertThat(registry.getTimers().get(SETUP_TASK_METRIC_NAME).getCount()).isGreaterThanOrEqualTo(1); assertThat(registry.getTimers().get(FINISH_TASK_METRIC_NAME).getCount()).isGreaterThanOrEqualTo(1); }