@SuppressWarnings("unchecked") static <T extends Metric> T getMetric(Method method, String name) { String metricName = String.format(METRIC_NAME_TEMPLATE, method.getDeclaringClass().getName(), method.getName(), name); return (T) getMetricRegistry().getMetrics().get(metricName); }
private <T> Optional<T> getMetric(String name, Class<T> metricType) { Metric m = registry.getMetrics().get(name); if (m != null) { assertThat("Metric " + name, m, instanceOf(metricType)); return Optional.of(metricType.cast(m)); } else { return Optional.empty(); } }
private <T> Map<String, T> singleEntry(final String name, final MetricRegistry metricRegistry, final Function<Metric, T> metricMapper) { return ofNullable(metricRegistry.getMetrics().get(name)) .map(metric -> singletonMap(name, metricMapper.apply(metric))) .orElseGet(Collections::emptyMap); }
@Override public void serialize(MetricRegistry metricRegistry, JsonGenerator json, SerializerProvider provider)throws IOException { json.writeStartObject(); for(Map.Entry<String, Metric> entry : metricRegistry.getMetrics().entrySet()) { json.writeObjectField(entry.getKey(), entry.getValue()); } json.writeEndObject(); } }
@GET @Path("{registry}") @Produces(MediaType.APPLICATION_JSON) public Object getJson(@PathParam("registry") final String registry, @Context final SecurityContext securityContext, @Context final UriInfo uriInfo) { securityValidator.checkSecurity(securityContext, uriInfo); return findRegistry(registry).getMetrics().entrySet().stream() .collect(toMap(Map.Entry::getKey, it -> map(it.getValue()))); }
@GET @Path("{registry}") @Produces(MediaType.TEXT_PLAIN) public String getText(@PathParam("registry") final String registry, @Context final SecurityContext securityContext, @Context final UriInfo uriInfo) { securityValidator.checkSecurity(securityContext, uriInfo); final MetricRegistry metricRegistry = findRegistry(registry); return prometheus.toText(metricRegistry, registry, metricRegistry.getMetrics()).toString(); }
@GET @Produces(MediaType.APPLICATION_JSON) public Object getJson(@Context final SecurityContext securityContext, @Context final UriInfo uriInfo) { securityValidator.checkSecurity(securityContext, uriInfo); return Stream.of(MetricRegistry.Type.values()) .collect(toMap(MetricRegistry.Type::getName, it -> findRegistry(it.getName()).getMetrics().entrySet().stream() .collect(toMap(Map.Entry::getKey, m -> map(m.getValue()))))); }
private void writeMetricsAsPrometheus(StringBuilder builder, String registryName, MetricRegistry registry, String metricName) { writeMetricMapAsPrometheus(builder, registryName, Collections.singletonMap(metricName, registry.getMetrics().get(metricName)), registry.getMetadata()); }
@Test public void metricMethodsWithDefaultNamingConvention() { assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(metricNames()))); } }
@Test public void timerFieldsWithDefaultNamingConvention() { assertThat("Timers are not registered correctly", registry.getMetrics().keySet(), is(equalTo(metricNames()))); } }
@GET @Produces(MediaType.TEXT_PLAIN) public String getText(@Context final SecurityContext securityContext, @Context final UriInfo uriInfo) { securityValidator.checkSecurity(securityContext, uriInfo); return Stream.of(MetricRegistry.Type.values()) .map(type -> { final MetricRegistry metricRegistry = findRegistry(type.getName()); return prometheus.toText(metricRegistry, type.getName(), metricRegistry.getMetrics()); }) .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString(); }
@Test @InSequence(1) public void metricsMethodNotCalledYet() { assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames()))); }
private void writeMetricsAsPrometheus(StringBuilder builder, String registryName, MetricRegistry registry) { writeMetricMapAsPrometheus(builder, registryName, registry.getMetrics(), registry.getMetadata()); }
@Test @InSequence(1) public void overloadedTimedMethodNotCalledYet() { Assert.assertTrue("Metrics are not registered correctly", registry.getMetrics().keySet().containsAll(absoluteMetricNames())); // Make sure that all the timers haven't been called yet assertThat("Timer counts are incorrect", registry.getTimers().values(), hasItem(Matchers.<Timer> hasProperty("count", equalTo(0L)))); }
@Test @InSequence(2) public void callOverloadedTimedMethodOnce() { Assert.assertTrue("Metrics are not registered correctly", registry.getMetrics().keySet().containsAll(absoluteMetricNames())); // Call the timed methods and assert they've all been timed once bean.overloadedTimedMethod(); bean.overloadedTimedMethod("string"); bean.overloadedTimedMethod(new Object()); bean.overloadedTimedMethod(Arrays.asList("string1", "string2")); assertThat("Timer counts are incorrect", registry.getTimers().values(), hasItem(Matchers.<Timer> hasProperty("count", equalTo(1L)))); } }
private Timer findTimer(final Executable executable) { if (timers == null) { synchronized (this) { if (timers == null) { timers = new ConcurrentHashMap<>(); } } } Timer timer = timers.get(executable); if (timer == null) { final AnnotatedType<?> type = beanManager.createAnnotatedType(bean.getBeanClass()); final Timed timed = Stream.concat(type.getMethods().stream(), type.getConstructors().stream()) .filter(it -> it.getJavaMember().equals(executable)) .findFirst() .map(m -> m.getAnnotation(Timed.class)) .orElse(null); final String name = Names.findName( Modifier.isAbstract(executable.getDeclaringClass().getModifiers()) ? type.getJavaClass() : executable.getDeclaringClass(), executable, timed == null ? null : timed.name(), timed != null && timed.absolute(), ofNullable(type.getAnnotation(Timed.class)).map(Timed::name).orElse("")); timer = Timer.class.cast(registry.getMetrics().get(name)); if (timer == null) { throw new IllegalStateException("No timer with name [" + name + "] found in registry [" + registry + "]"); } timers.putIfAbsent(executable, timer); } return timer; } }
private Meta findCounter(final Executable executable) { if (counters == null) { synchronized (this) { if (counters == null) { counters = new ConcurrentHashMap<>(); } } } Meta meta = counters.get(executable); if (meta == null) { final AnnotatedType<?> type = beanManager.createAnnotatedType(bean.getBeanClass()); final Counted counted = Stream.concat(type.getMethods().stream(), type.getConstructors().stream()) .filter(it -> it.getJavaMember().equals(executable)) .findFirst() .map(m -> m.getAnnotation(Counted.class)) .orElse(null); final String name = Names.findName( Modifier.isAbstract(executable.getDeclaringClass().getModifiers()) ? type.getJavaClass() : executable.getDeclaringClass(), executable, counted == null ? null : counted.name(), counted != null && counted.absolute(), ofNullable(type.getAnnotation(Counted.class)).map(Counted::name).orElse("")); final Counter counter = Counter.class.cast(registry.getMetrics().get(name)); if (counter == null) { throw new IllegalStateException("No counter with name [" + name + "] found in registry [" + registry + "]"); } meta = new Meta(counter, ofNullable(counted).orElseGet(() -> type.getAnnotation(Counted.class)).monotonic()); counters.putIfAbsent(executable, meta); } return meta; }
@Test @InSequence(2) public void callMetricsMethodOnce() { assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames()))); // Call the monitored method and assert it's been instrumented bean.metricsMethod(); // Make sure that the metrics have been called assertThat("Counter count is incorrect", registry.getCounters().get(absoluteMetricName("counter")).getCount(), is(equalTo(1L))); assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("meter")).getCount(), is(equalTo(1L))); assertThat("Timer count is incorrect", registry.getTimers().get(absoluteMetricName("timer")).getCount(), is(equalTo(1L))); // Let's call the gauge at the end as Weld is intercepting the gauge // invocation while OWB not assertThat("Gauge value is incorrect", registry.getGauges().get(absoluteMetricName("gauge")).getValue(), hasToString((equalTo("value")))); } }
@Test @InSequence(2) public void callCachedMethodMultipleTimes() { assertThat("Metrics are not registered correctly", registry.getMetrics(), allOf( hasKey(CALLS_METRIC), hasKey(HITS_METRIC), hasKey(CACHE_HITS_METRIC) ) ); Timer calls = registry.getTimers().get(CALLS_METRIC); Meter hits = registry.getMeters().get(HITS_METRIC); @SuppressWarnings("unchecked") Gauge<Double> gauge = (Gauge<Double>) registry.getGauges().get(CACHE_HITS_METRIC); long count = 10 + Math.round(Math.random() * 10); for (int i = 0; i < count; i++) { bean.cachedMethod((Math.random() < 0.5)); } assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo((double) hits.getCount() / (double) calls.getCount()))); } }
@Test @InSequence(1) public void cachedMethodNotCalledYet() { assertThat("Metrics are not registered correctly", registry.getMetrics(), allOf( hasKey(CALLS_METRIC), hasKey(HITS_METRIC), hasKey(CACHE_HITS_METRIC) ) ); Timer calls = registry.getTimers().get(CALLS_METRIC); Meter hits = registry.getMeters().get(HITS_METRIC); @SuppressWarnings("unchecked") Gauge<Double> gauge = (Gauge<Double>) registry.getGauges().get(CACHE_HITS_METRIC); assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) hits.getCount() / (double) calls.getCount())))); }