@Override public long getNumberOfSuccessfulCalls() { return successfulCallsTimer.getCount(); }
public static Map<String, Long> dumpMetrics(MetricContext context) { Map<String, Long> output = new HashMap<>(); for (Map.Entry<String, Meter> entry : context.getMeters().entrySet()) { output.put(entry.getKey(), entry.getValue().getCount()); } for (Map.Entry<String, Timer> entry : context.getTimers().entrySet()) { output.put(entry.getKey(), entry.getValue().getCount()); } return output; }
/** * Export dropwizard Timer as a histogram. Use TIME_UNIT as time unit. */ private MetricFamilySamples fromTimer(List<Map.Entry<MetricName, Timer>> histogramsWithSameName) { final SummaryMetricFamily summaryMetricFamily = getSummaryMetricFamily(histogramsWithSameName, "_seconds"); for (Map.Entry<MetricName, Timer> entry : histogramsWithSameName) { addSummaryMetric(summaryMetricFamily, entry.getKey(), entry.getValue().getSnapshot(), SECONDS_IN_NANOS, entry.getValue().getCount()); } return summaryMetricFamily; }
private void printTimer(String name, Timer timer, int maxNameLength, StringBuilder sb) { final Snapshot snapshot = timer.getSnapshot(); sb.append(String.format("%" + maxNameLength + "s | ", name)); sb.append(formatCount(timer.getCount())); printTimerSnapshot(snapshot, sb); printMetered(timer, sb); sb.append('\n'); }
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; }
@Override protected void reportInContext(MetricContext context, SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { for (Map.Entry<String, Gauge> entry : gauges.entrySet()) { Gauge gauge = entry.getValue(); if (gauge.getValue() instanceof Long || gauge.getValue() instanceof Integer || gauge.getValue() instanceof Short || gauge.getValue() instanceof Byte) reportValue(context, entry.getKey(), ((Number) gauge.getValue()).longValue()); } for (Map.Entry<String, Counter> entry : counters.entrySet()) { reportCount(context, entry.getKey(), entry.getValue().getCount()); } for (Map.Entry<String, Meter> entry : meters.entrySet()) { reportCount(context, entry.getKey(), entry.getValue().getCount()); } for (Map.Entry<String, Histogram> entry : histograms.entrySet()) { reportCount(context, entry.getKey(), entry.getValue().getCount()); } for (Map.Entry<String, Timer> entry : timers.entrySet()) { reportCount(context, entry.getKey(), entry.getValue().getCount()); } }
public static Timer timer(long count, double meanRate, double m1Rate, double m5Rate, double m15Rate, Snapshot snapshot) { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(count); when(timer.getMeanRate()).thenReturn(meanRate); when(timer.getOneMinuteRate()).thenReturn(m1Rate); when(timer.getFiveMinuteRate()).thenReturn(m5Rate); when(timer.getFifteenMinuteRate()).thenReturn(m15Rate); when(timer.getSnapshot()).thenReturn(snapshot); return timer; }
public static TimerRateMetricsResponse buildTimerMap(Timer t) { final TimerRateMetricsResponse result = new TimerRateMetricsResponse(); if (t == null) { return result; } final TimerMetricsResponse time = new TimerMetricsResponse(); time.max = TimeUnit.MICROSECONDS.convert(t.getSnapshot().getMax(), TimeUnit.NANOSECONDS); time.min = TimeUnit.MICROSECONDS.convert(t.getSnapshot().getMin(), TimeUnit.NANOSECONDS); time.mean = TimeUnit.MICROSECONDS.convert((long) t.getSnapshot().getMean(), TimeUnit.NANOSECONDS); time.percentile95th = TimeUnit.MICROSECONDS.convert((long) t.getSnapshot().get95thPercentile(), TimeUnit.NANOSECONDS); time.percentile98th = TimeUnit.MICROSECONDS.convert((long) t.getSnapshot().get98thPercentile(), TimeUnit.NANOSECONDS); time.percentile99th = TimeUnit.MICROSECONDS.convert((long) t.getSnapshot().get99thPercentile(), TimeUnit.NANOSECONDS); time.stdDev = TimeUnit.MICROSECONDS.convert((long) t.getSnapshot().getStdDev(), TimeUnit.NANOSECONDS); final RateMetricsResponse rate = new RateMetricsResponse(); rate.oneMinute = t.getOneMinuteRate(); rate.fiveMinute = t.getFiveMinuteRate(); rate.fifteenMinute = t.getFifteenMinuteRate(); rate.total = t.getCount(); rate.mean = t.getMeanRate(); result.time = time; result.rate = rate; result.rateUnit = "events/second"; result.durationUnit = TimeUnit.MICROSECONDS.toString().toLowerCase(Locale.ENGLISH); return result; }
@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 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)); }
private void printTimer(Timer timer) { final Snapshot snapshot = timer.getSnapshot(); this.outputBufferPrintStream.printf(locale, " count = %d%n", timer.getCount()); this.outputBufferPrintStream.printf(locale, " mean rate = %2.2f calls/%s%n", convertRate(timer.getMeanRate()), getRateUnit()); this.outputBufferPrintStream.printf(locale, " 1-minute rate = %2.2f calls/%s%n", convertRate(timer.getOneMinuteRate()), getRateUnit()); this.outputBufferPrintStream.printf(locale, " 5-minute rate = %2.2f calls/%s%n", convertRate(timer.getFiveMinuteRate()), getRateUnit()); this.outputBufferPrintStream.printf(locale, " 15-minute rate = %2.2f calls/%s%n", convertRate(timer.getFifteenMinuteRate()), getRateUnit()); this.outputBufferPrintStream.printf(locale, " min = %2.2f %s%n", convertDuration(snapshot.getMin()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " max = %2.2f %s%n", convertDuration(snapshot.getMax()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " mean = %2.2f %s%n", convertDuration(snapshot.getMean()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " stddev = %2.2f %s%n", convertDuration(snapshot.getStdDev()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " median = %2.2f %s%n", convertDuration(snapshot.getMedian()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " 75%% <= %2.2f %s%n", convertDuration(snapshot.get75thPercentile()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " 95%% <= %2.2f %s%n", convertDuration(snapshot.get95thPercentile()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " 98%% <= %2.2f %s%n", convertDuration(snapshot.get98thPercentile()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " 99%% <= %2.2f %s%n", convertDuration(snapshot.get99thPercentile()), getDurationUnit()); this.outputBufferPrintStream.printf(locale, " 99.9%% <= %2.2f %s%n", convertDuration(snapshot.get999thPercentile()), getDurationUnit()); }
private void verifyTimerCreated(int count) { final MetricName timerName = name("response_time") .operationType("jdbc") .operationName("Report Me") .build(); assertThat(registry.getTimers()).containsKey(timerName); final Timer timer = registry.getTimers().get(timerName); assertThat(timer.getCount()).isEqualTo(count); final MetricName allTimerName = name("response_time") .operationType("jdbc") .operationName("All") .build(); assertThat(registry.getTimers()).containsKey(allTimerName); final Timer allTimer = registry.getTimers().get(allTimerName); assertThat(allTimer.getCount()).isEqualTo(count); } }
@Test public void testSuccessfulWritesWithLimiter () { MockThrottledHttpClient client = new MockThrottledHttpClient(createMockBroker()); MockRequestBuilder requestBuilder = new MockRequestBuilder(); MockResponseHandler responseHandler = new MockResponseHandler(); MockAsyncHttpWriterBuilder builder = new MockAsyncHttpWriterBuilder(client, requestBuilder, responseHandler); TestAsyncHttpWriter asyncHttpWriter = new TestAsyncHttpWriter(builder); List<MockWriteCallback> callbacks = new ArrayList<>(); for (int i = 0; i < 50; i++) { MockWriteCallback callback = new MockWriteCallback(); callbacks.add(callback); asyncHttpWriter.write(new Object(), callback); } try { asyncHttpWriter.close(); } catch (IOException e) { Assert.fail("Close failed"); } // Assert all successful callbacks are invoked for (MockWriteCallback callback : callbacks) { Assert.assertTrue(callback.isSuccess); } Assert.assertTrue(client.getSendTimer().getCount() == 50); Assert.assertTrue(client.isCloseCalled); }
private void printTimer(Timer timer) { final Snapshot snapshot = timer.getSnapshot(); printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", timer.getCount())); printIfEnabled(MetricAttribute.MEAN_RATE, String.format(locale, " mean rate = %2.2f calls/%s", convertRate(timer.getMeanRate()), getRateUnit())); printIfEnabled(MetricAttribute.M1_RATE, String.format(locale, " 1-minute rate = %2.2f calls/%s", convertRate(timer.getOneMinuteRate()), getRateUnit())); printIfEnabled(MetricAttribute.M5_RATE, String.format(locale, " 5-minute rate = %2.2f calls/%s", convertRate(timer.getFiveMinuteRate()), getRateUnit())); printIfEnabled(MetricAttribute.M15_RATE, String.format(locale, " 15-minute rate = %2.2f calls/%s", convertRate(timer.getFifteenMinuteRate()), getRateUnit())); printIfEnabled(MetricAttribute.MIN, String.format(locale, " min = %2.2f %s", convertDuration(snapshot.getMin()), getDurationUnit())); printIfEnabled(MetricAttribute.MAX, String.format(locale, " max = %2.2f %s", convertDuration(snapshot.getMax()), getDurationUnit())); printIfEnabled(MetricAttribute.MEAN, String.format(locale, " mean = %2.2f %s", convertDuration(snapshot.getMean()), getDurationUnit())); printIfEnabled(MetricAttribute.STDDEV, String.format(locale, " stddev = %2.2f %s", convertDuration(snapshot.getStdDev()), getDurationUnit())); printIfEnabled(MetricAttribute.P50, String.format(locale, " median = %2.2f %s", convertDuration(snapshot.getMedian()), getDurationUnit())); printIfEnabled(MetricAttribute.P75, String.format(locale, " 75%% <= %2.2f %s", convertDuration(snapshot.get75thPercentile()), getDurationUnit())); printIfEnabled(MetricAttribute.P95, String.format(locale, " 95%% <= %2.2f %s", convertDuration(snapshot.get95thPercentile()), getDurationUnit())); printIfEnabled(MetricAttribute.P98, String.format(locale, " 98%% <= %2.2f %s", convertDuration(snapshot.get98thPercentile()), getDurationUnit())); printIfEnabled(MetricAttribute.P99, String.format(locale, " 99%% <= %2.2f %s", convertDuration(snapshot.get99thPercentile()), getDurationUnit())); printIfEnabled(MetricAttribute.P999, String.format(locale, " 99.9%% <= %2.2f %s", convertDuration(snapshot.get999thPercentile()), getDurationUnit())); }
@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); }
@Test public void testRecordSqlStatement() throws Exception { final SpanContextInformation spanContext = requestMonitor .monitor(new MonitoredMethodRequest(configuration, "testRecordSqlStatement", () -> { testDao.executeStatement(); })); final Map<MetricName, Timer> timers = metric2Registry.getTimers(); final String message = timers.keySet().toString(); assertTrue(message, timers.size() > 1); assertEquals(message, 1, timers.get(name("response_time").operationType("jdbc").operationName("ConnectionMonitoringTransformerTest$TestDao#executeStatement").build()).getCount()); assertEquals(message, 1, timers.get(name("response_time").operationType("jdbc").operationName("All").build()).getCount()); final CallStackElement callStack = spanContext.getCallTree(); assertEquals("testRecordSqlStatement", callStack.getSignature()); assertEquals("void org.stagemonitor.jdbc.ConnectionMonitoringTransformerTest$TestDao.executeStatement()", callStack.getChildren().get(0).getSignature()); assertEquals("SELECT * from STAGEMONITOR ", callStack.getChildren().get(0).getChildren().get(0).getSignature()); }
@Test public void testRequestMonitorMvcRequest() throws Exception { when(servletPlugin.isMonitorOnlySpringMvcRequests()).thenReturn(false); MonitoredHttpRequest monitoredRequest = createMonitoredHttpRequest(mvcRequest); final SpanContextInformation spanContext = requestMonitor.monitor(monitoredRequest); assertEquals("Test Get Request Name", spanContext.getOperationName()); assertEquals(1, registry.timer(getResponseTimeMetricName(spanContext.getOperationName(), "http")).getCount()); assertEquals("Test Get Request Name", spanContext.getOperationName()); assertEquals("/test/requestName", tags.get(Tags.HTTP_URL.getKey())); assertEquals("GET", tags.get("method")); assertThat(registry.getTimers()).containsKey(name("response_time").operationName("Test Get Request Name").operationType("http").build()); }
@Test public void testMetrics() throws Exception { ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig(); guiceServletConfig.initialize(ConfigFactory.empty()); Injector injector = guiceServletConfig.getInjector(); LimiterServerResource limiterServer = injector.getInstance(LimiterServerResource.class); PermitRequest request = new PermitRequest(); request.setPermits(10); request.setResource("myResource"); limiterServer.getSync(new ComplexResourceKey<>(request, new EmptyRecord())); limiterServer.getSync(new ComplexResourceKey<>(request, new EmptyRecord())); limiterServer.getSync(new ComplexResourceKey<>(request, new EmptyRecord())); MetricContext metricContext = limiterServer.metricContext; Timer timer = metricContext.timer(LimiterServerResource.REQUEST_TIMER_NAME); Assert.assertEquals(timer.getCount(), 3); }
private void reportTimer(long timestamp, String name, Timer timer) { final Snapshot snapshot = timer.getSnapshot(); report(timestamp, name, "count,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", timerFormat, timer.getCount(), convertDuration(snapshot.getMax()), convertDuration(snapshot.getMean()), convertDuration(snapshot.getMin()), convertDuration(snapshot.getStdDev()), convertDuration(snapshot.getMedian()), convertDuration(snapshot.get75thPercentile()), convertDuration(snapshot.get95thPercentile()), convertDuration(snapshot.get98thPercentile()), convertDuration(snapshot.get99thPercentile()), convertDuration(snapshot.get999thPercentile()), convertRate(timer.getMeanRate()), convertRate(timer.getOneMinuteRate()), convertRate(timer.getFiveMinuteRate()), convertRate(timer.getFifteenMinuteRate()), getRateUnit(), getDurationUnit()); }