Java Code Examples for org.eclipse.microprofile.metrics.Counter

The following examples show how to use org.eclipse.microprofile.metrics.Counter. These examples are extracted from open source projects. 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
@Test
public void testMetricsConnector() {
    testConnector.send(MetricsTestBean.CONNECTOR_IN, Message.of("one"));
    testConnector.send(MetricsTestBean.CONNECTOR_IN, Message.of("two"));
    
    assertEquals("one-test-1", testConnector.get(MetricsTestBean.CONNECTOR_OUT).getPayload());
    assertEquals("one-test-2", testConnector.get(MetricsTestBean.CONNECTOR_OUT).getPayload());
    assertEquals("two-test-1", testConnector.get(MetricsTestBean.CONNECTOR_OUT).getPayload());
    assertEquals("two-test-2", testConnector.get(MetricsTestBean.CONNECTOR_OUT).getPayload());
    
    Counter channelInCounter = getMessageCounterForChannel(MetricsTestBean.CONNECTOR_IN);
    Counter channelProcessCounter = getMessageCounterForChannel(MetricsTestBean.CONNECTOR_PROCESS);
    Counter channelOutCounter = getMessageCounterForChannel(MetricsTestBean.CONNECTOR_OUT);
    
    assertEquals(2, channelInCounter.getCount());
    assertEquals(2, channelProcessCounter.getCount());
    assertEquals(4, channelOutCounter.getCount());
}
 
Example 2
Source Project: smallrye-metrics   Source File: MetricsRegistryImpl.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isSameType(Metric metricInstance, MetricType type) {
    switch (type) {
        case CONCURRENT_GAUGE:
            return metricInstance instanceof ConcurrentGauge;
        case GAUGE:
            return metricInstance instanceof Gauge;
        case HISTOGRAM:
            return metricInstance instanceof Histogram;
        case TIMER:
            return metricInstance instanceof Timer;
        case METERED:
            return metricInstance instanceof Meter;
        case COUNTER:
            return metricInstance instanceof Counter;
        case SIMPLE_TIMER:
            return metricInstance instanceof SimpleTimer;
        default:
            throw new IllegalArgumentException();
    }
}
 
Example 3
Source Project: smallrye-metrics   Source File: MetricsRegistryImpl.java    License: Apache License 2.0 6 votes vote down vote up
private MetricType metricTypeFromClass(Class<?> in) {
    if (in.equals(Counter.class)) {
        return MetricType.COUNTER;
    } else if (in.equals(Gauge.class)) {
        return MetricType.GAUGE;
    } else if (in.equals(ConcurrentGauge.class)) {
        return MetricType.CONCURRENT_GAUGE;
    } else if (in.equals(Meter.class)) {
        return MetricType.METERED;
    } else if (in.equals(Timer.class)) {
        return MetricType.TIMER;
    } else if (in.equals(SimpleTimer.class)) {
        return MetricType.SIMPLE_TIMER;
    } else if (in.equals(Histogram.class)) {
        return MetricType.HISTOGRAM;
    }
    return null;
}
 
Example 4
Source Project: smallrye-metrics   Source File: CountedInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object countedCallable(InvocationContext context, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getCounters(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    ids.stream()
            .map(metricID -> {
                Counter metric = registry.getCounters().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.COUNTER, metricID);
                }
                return metric;
            })
            .forEach(Counter::inc);
    return context.proceed();
}
 
Example 5
@Test
public void anonymousCounter() {
    registry.register("test", new Counter() {
        @Override
        public void inc() {
        }

        @Override
        public void inc(long l) {
        }

        @Override
        public long getCount() {
            return 3;
        }
    });
    Assert.assertEquals(3L, registry.getCounter(new MetricID("test")).getCount());
}
 
Example 6
/**
 * Given a Counter,
 * check that the statistics from OpenMetricsExporter will not be scaled in any way.
 */
@Test
public void counter_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("counter1")
            .withType(MetricType.COUNTER)
            .build();
    Counter metric = registry.counter(metadata);
    metric.inc(30);
    metric.inc(40);
    metric.inc(50);

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter1")).toString();

    Assert.assertThat(exported, containsString("application_counter1_total 120.0"));
}
 
Example 7
/**
 * Given a Counter,
 * check that the statistics from JsonExporter will not be scaled in any way.
 */
@Test
public void counter_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("counter1")
            .withType(MetricType.COUNTER)
            .build();
    Counter metric = registry.counter(metadata);
    metric.inc(10);
    metric.inc(20);
    metric.inc(30);

    JsonExporter exporter = new JsonExporter();
    String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter1")).toString();

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject();
    assertEquals(60, json.getInt("counter1"));
}
 
Example 8
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCounters() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Counter counterWithoutTags = registry.counter("mycounter");
    Counter counterRed = registry.counter("mycounter", new Tag("color", "red"));
    Counter counterBlue = registry.counter("mycounter", new Tag("color", "blue"), new Tag("foo", "bar"));

    counterWithoutTags.inc(1);
    counterRed.inc(2);
    counterBlue.inc(3);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mycounter").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    assertEquals(1, json.getInt("mycounter"));
    assertEquals(2, json.getInt("mycounter;color=red"));
    assertEquals(3, json.getInt("mycounter;color=blue;foo=bar"));
}
 
Example 9
Source Project: quarkus   Source File: AgroalMetricsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDefaultDS() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "default")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "default")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

    try (Connection connection = defaultDS.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1");
        }
    }

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example 10
Source Project: quarkus   Source File: AgroalMetricsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDs1() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "ds1")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "ds1")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

    try (Connection connection = ds1.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1");
        }
    }

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example 11
Source Project: microprofile-metrics   Source File: CountedClassBeanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callCountedMethodsOnce() { 
    assertThat("Counters are not registered correctly", registry.getCounters().keySet(), is(equalTo(counterMIDs)));

    // Call the counted methods and assert they've been incremented
    bean.countedMethodOne();
    bean.countedMethodTwo();
    // Let's call the non-public methods as well
    bean.countedMethodProtected();
    bean.countedMethodPackagedPrivate();

    // Make sure that the counters have been incremented
    assertThat("Method counter counts are incorrect", registry.getCounters(METHOD_COUNTERS).values(),
            everyItem(Matchers.<Counter> hasProperty("count", equalTo(1L))));

    assertThat("Constructor's metric should be incremented at least once",
        registry.getCounter(constructorMID).getCount(), is(greaterThanOrEqualTo(1L)));
}
 
Example 12
Source Project: microprofile-metrics   Source File: MetricRegistryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void registerTest() {
    metrics.register("regCountTemp", countTemp);
    assertExists(Counter.class, new MetricID("regCountTemp"));

    metrics.register("regHistoTemp", histoTemp);
    assertExists(Histogram.class, new MetricID("regHistoTemp"));

    metrics.register("regTimerTemp", timerTemp);
    assertExists(Timer.class, new MetricID("regTimerTemp"));

    metrics.register("regSimpleTimerTemp", simpleTimerTemp);
    assertExists(SimpleTimer.class, new MetricID("regSimpleTimerTemp"));

    metrics.register("regConcurrentGaugeTemp", concurrentGaugeTemp);
    assertExists(ConcurrentGauge.class, new MetricID("regConcurrentGaugeTemp"));

    metrics.register("regMeterTemp", meterTemp);
    assertExists(Meter.class, new MetricID("regMeterTemp"));
}
 
Example 13
Source Project: microprofile-metrics   Source File: MetricRegistryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(4)
public void useExistingMetaDataTest() {
    String displayName = "displayCounterFoo";
    String metricName = "counterFoo";

    //first to register a "complex" metadata
    metrics.counter(Metadata.builder().withName(metricName).withDisplayName(displayName).withType(MetricType.COUNTER).build());

    Tag purpleTag = new Tag("colour","purple");
    //creates with a simple/template metadata or uses an existing one.
    metrics.counter(metricName, purpleTag);

    //check both counters have been registered
    assertExists(Counter.class, new MetricID(metricName));
    assertExists(Counter.class, new MetricID(metricName, purpleTag));

    //check that the "original" metadata wasn't replaced by the empty default metadata
    Assert.assertEquals(metrics.getMetadata(metricName).getDisplayName(), displayName);
}
 
Example 14
Source Project: microprofile-metrics   Source File: TagsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void lastTagValueTest() {
    
    Tag tagColour = new Tag("colour","red");
    Tag tagColourTwo = new Tag("colour","blue");
    
    String counterName = "org.eclipse.microprofile.metrics.tck.TagTest.counter";
    Counter counter = registry.counter(counterName, tagColour, tagColourTwo);
    
    //MetricID that only has colour=blue... the last tag value to be passed in
    MetricID counterMID = new MetricID(counterName, tagColourTwo);
    
    //check the metric is registered
    assertThat("Counter is not registered correctly", registry.getCounter(counterMID), notNullValue());
}
 
Example 15
Source Project: microprofile-metrics   Source File: TagsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(3)
public void counterTagsTest() {
    
    Tag tagEarth = new Tag("planet", "earth");
    Tag tagRed = new Tag("colour", "red");
    Tag tagBlue = new Tag("colour", "blue");
    
    String counterName = "org.eclipse.microprofile.metrics.tck.TagTest.counterColour";
    
    Counter counterColour = registry.counter(counterName);
    Counter counterRed = registry.counter(counterName,tagEarth,tagRed);
    Counter counterBlue = registry.counter(counterName,tagEarth,tagBlue);
    
    MetricID counterColourMID = new MetricID(counterName);
    MetricID counterRedMID = new MetricID(counterName, tagEarth,tagRed);
    MetricID counterBlueMID = new MetricID(counterName, tagEarth,tagBlue);
    
    //check multi-dimensional metrics are registered
    assertThat("Counter is not registered correctly", registry.getCounter(counterColourMID), notNullValue());
    assertThat("Counter is not registered correctly", registry.getCounter(counterRedMID), notNullValue());
    assertThat("Counter is not registered correctly", registry.getCounter(counterBlueMID), notNullValue());
}
 
Example 16
@Test
@InSequence(2)
public void incrementCounterTagFields() {
    Counter counterOne = registry.getCounter(counterMID);
    assertThat("Counter is not registered correctly", counterOne, notNullValue());

    Counter counterTwo = registry.getCounter(counterTwoMID);
    assertThat("Counter is not registered correctly", counterTwo, notNullValue());

    Counter counterThree = registry.getCounter(counterThreeMID);
    assertThat("Counter is not registered correctly", counterThree, notNullValue());

    // Call the increment method and assert the counter is up-to-date
    long value = Math.round(Math.random() * Long.MAX_VALUE);
    bean.incrementOne(value);

    long valueTwo = Math.round(Math.random() * Long.MAX_VALUE);
    bean.incrementTwo(valueTwo);

    long valueThree = Math.round(Math.random() * Long.MAX_VALUE);
    bean.incrementThree(valueThree);

    assertThat("Counter value is incorrect", counterOne.getCount(), is(equalTo(value)));
    assertThat("Counter value is incorrect", counterTwo.getCount(), is(equalTo(valueTwo)));
    assertThat("Counter value is incorrect", counterThree.getCount(), is(equalTo(valueThree)));
}
 
Example 17
@Test
@InSequence(1)
public void countersNotIncrementedYet() {
    assertThat("Counters are not registered correctly", registry.getCounters(),
        allOf(
            hasKey(counter1MID),
            hasKey(counter2MID),
            not(hasKey(notRegMID))
        )
    );
    Counter counter1 = registry.getCounter(counter1MID);
    Counter counter2 = registry.getCounter(counter2MID);

    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(ratioGaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) counter1.getCount()) / ((double) counter2.getCount()))));
}
 
Example 18
@Test
@InSequence(2)
public void incrementCountersFromRegistry() {
    assertThat("Counters are not registered correctly", registry.getCounters(),
        allOf(
            hasKey(counter1MID),
            hasKey(counter2MID),
            not(hasKey(notRegMID))
        )
    );
    Counter counter1 = registry.getCounter(counter1MID);
    Counter counter2 = registry.getCounter(counter2MID);

    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(ratioGaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    counter1.inc(Math.round(Math.random() * Integer.MAX_VALUE));
    counter2.inc(Math.round(Math.random() * Integer.MAX_VALUE));

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) counter1.getCount()) / ((double) counter2.getCount()))));
}
 
Example 19
private Counter counterOf(String name) {
    MetricID metricID = new MetricID(name);
    Counter counter = registry.getCounters().get(metricID);
    if (counter == null) {
        synchronized (operation) {
            counter = registry.getCounters().get(metricID);
            if (counter == null) {
                counter = registry.counter(metadataOf(name, MetricType.COUNTER));
            }
        }
    }
    return counter;
}
 
Example 20
@Test
public void testMetricsInApp() {
    Awaitility.await().until(testBean::getInAppMessagesReceived, equalTo(6));
    
    Counter appACounter = getMessageCounterForChannel(MetricsTestBean.CHANNEL_APP_A);
    Counter appBCounter = getMessageCounterForChannel(MetricsTestBean.CHANNEL_APP_B);
    
    assertEquals(3, appACounter.getCount());
    assertEquals(6, appBCounter.getCount());
}
 
Example 21
private Counter getMessageCounterForChannel(String channel) {
    Map<MetricID, Counter> counters = metricRegistry.getCounters((id, m) -> id.getName().equals("mp.messaging.message.count")
            && id.getTags().getOrDefault("channel", "").equals(channel));
    
    assertThat(counters.entrySet(), hasSize(1));
    
    return counters.values().iterator().next();
}
 
Example 22
@Test
public void test() {
    Counter metricFromConstructor = registry.getCounters()
            .get(new MetricID(
                    "io.smallrye.metrics.test.initialization.Initialization_Counter_Constructor_Test" +
                            "$BeanWithCounter_Constructor.BeanWithCounter_Constructor"));
    assertNotNull(metricFromConstructor);
    assertEquals(1, registry.getCounters().size());
}
 
Example 23
@Produces
@Metric(name = "c1", absolute = true)
public Counter producer() {
    return new CounterImpl() {
        @Override
        public long getCount() {
            return 111;
        }
    };
}
 
Example 24
@Test
public void test() {
    MetricID metricID = new MetricID("counter1");
    // check eager initialization here
    assertTrue(registry.getCounters().containsKey(metricID));
    assertEquals(0, registry.getCounters().get(metricID).getCount());
    bean.addDataToCounter();
    Counter counter = registry.getCounters().get(metricID);
    assertEquals(1, counter.getCount());
}
 
Example 25
@Inject
public void increaseCountersOnInjecting(
        @Metric(name = "mycounter", absolute = true, tags = { "k=v1" }) Counter counter1,
        @Metric(name = "mycounter", absolute = true, tags = { "k=v2" }) Counter counter2) {
    counter1.inc(2);
    counter2.inc(3);
}
 
Example 26
Source Project: smallrye-metrics   Source File: JsonExporter.java    License: Apache License 2.0 5 votes vote down vote up
private Number getValueFromMetric(Metric theMetric, String name) {
    if (theMetric instanceof Gauge) {
        Number value = (Number) ((Gauge) theMetric).getValue();
        if (value != null) {
            return value;
        } else {
            return 0;
        }
    } else if (theMetric instanceof Counter) {
        return ((Counter) theMetric).getCount();
    } else {
        return null;
    }
}
 
Example 27
Source Project: smallrye-metrics   Source File: OpenMetricsExporter.java    License: Apache License 2.0 5 votes vote down vote up
private void createSimpleValueLine(StringBuilder sb, MetricRegistry.Type scope, String key, Metadata md, Metric metric,
        String suffix, Map<String, String> tags) {

    // value line
    fillBaseName(sb, scope, key, suffix, md);
    // append the base unit only in case that the key wasn't overridden
    if (getOpenMetricsKeyOverride(md) == null) {
        String unit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(md.unit());
        if (!unit.equals(NONE)) {
            sb.append(USCORE).append(unit);
        }
    }

    addTags(sb, tags, scope, md);

    double valIn;
    if (md.getTypeRaw().equals(MetricType.GAUGE)) {
        Number value1 = (Number) ((Gauge) metric).getValue();
        if (value1 != null) {
            valIn = value1.doubleValue();
        } else {
            valIn = Double.NaN;
        }
    } else {
        valIn = (double) ((Counter) metric).getCount();
    }

    Double value = OpenMetricsUnit.scaleToBase(md.unit().orElse(NONE), valIn);
    sb.append(SPACE).append(value).append(LF);

}
 
Example 28
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void exportCounters() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata
            .builder()
            .withType(MetricType.COUNTER)
            .withName("mycounter")
            .withDescription("awesome")
            .build();
    Tag blueTag = new Tag("color", "blue");
    Counter blueCounter = registry.counter(metadata, blueTag);
    Tag greenTag = new Tag("color", "green");
    Counter greenCounter = registry.counter(metadata, greenTag);

    blueCounter.inc(10);
    greenCounter.inc(20);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mycounter").toString();
    System.out.println(result);

    assertHasTypeLineExactlyOnce(result, "application_mycounter_total", "counter");
    assertHasHelpLineExactlyOnce(result, "application_mycounter_total", "awesome");

    assertHasValueLineExactlyOnce(result, "application_mycounter_total", "10.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mycounter_total", "20.0", greenTag);

}
 
Example 29
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test prependsScopeToOpenMetricsName in the ExtendedMetadata
 */
@Test
public void testMicroProfileScopeInTagsWithExtendedMetadata() {

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = new ExtendedMetadata("mycounter", "mycounter", "awesome", MetricType.COUNTER,
            "none", null, false, Optional.of(false));
    Tag colourTag = new Tag("color", "blue");
    Counter counterWithTag = registry.counter(metadata, colourTag);
    Counter counterWithoutTag = registry.counter(metadata);

    counterWithTag.inc(10);
    counterWithoutTag.inc(20);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mycounter").toString();
    System.out.println(result);

    Tag microProfileScopeTag = new Tag("microprofile_scope", MetricRegistry.Type.APPLICATION.getName().toLowerCase());

    assertHasTypeLineExactlyOnce(result, "mycounter_total", "counter");
    assertHasHelpLineExactlyOnce(result, "mycounter_total", "awesome");

    assertHasValueLineExactlyOnce(result, "mycounter_total", "10.0", colourTag, microProfileScopeTag);
    assertHasValueLineExactlyOnce(result, "mycounter_total", "20.0", microProfileScopeTag);
}
 
Example 30
Source Project: blog-tutorials   Source File: MetricsUpdates.java    License: MIT License 5 votes vote down vote up
public void updates() {
    Metadata metadata = Metadata
            .builder()
            .reusable(true)
            .withName("myMetric")
            .withUnit("seconds")
            .withDescription("counting seconds")
            .withType(MetricType.COUNTER)
            .build();

    Counter counterOne = metricRegistry.counter(metadata);
    Counter counterTwo = metricRegistry.counter(metadata);

}