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

The following examples show how to use org.eclipse.microprofile.metrics.MetricUnits. 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
@APIResponses(
        value = {
            @APIResponse(
                    responseCode = "404",
                    description = "We could not find anything",
                    content = @Content(mediaType = "text/plain"))
            ,
    @APIResponse(
                    responseCode = "200",
                    description = "We have a list of books",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = Properties.class)))})
@Operation(summary = "Outputs a list of books",
        description = "This method outputs a list of books")
@Timed(name = "get-all-books",
        description = "Monitor the time getAll Method takes",
        unit = MetricUnits.MILLISECONDS,
        absolute = true)
@GET
public Response getAll() {
    return Response.ok(bookService.getAll()).build();
}
 
Example 2
Source Project: quarkus-deep-dive   Source File: TodoResource.java    License: Apache License 2.0 6 votes vote down vote up
@PATCH
@Path("/{id}")
@Transactional
@Counted(name = "updateCount", monotonic = true, description = "How many update calls have been done.")
@Timed(name = "updateTime", description = "How long does the update method takes.", unit = MetricUnits.MILLISECONDS)
public Response update(@Valid Todo todo, @PathParam("id") Long id) {
    Todo entity = Todo.findById(id);
    if (entity == null) {
        throw new WebApplicationException("Item with id of " + id + " does not exist.", 404);
    }
    entity.id = id;
    entity.completed = todo.completed;
    entity.order = todo.order;
    entity.title = todo.title;
    entity.url = todo.url;
    return Response.ok(entity).build();
}
 
Example 3
/**
 * Given a Timer with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be correctly converted to SECONDS.
 */
@Test
public void timer_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("timer1")
            .withType(MetricType.TIMER)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Timer metric = registry.timer(metadata);
    metric.update(Duration.ofHours(1));
    metric.update(Duration.ofHours(2));
    metric.update(Duration.ofHours(3));

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

    Assert.assertThat(exported, containsString("application_timer1_seconds{quantile=\"0.5\"} 7200.0"));
    Assert.assertThat(exported, containsString("application_timer1_mean_seconds 7200.0"));
    Assert.assertThat(exported, containsString("application_timer1_min_seconds 3600.0"));
    Assert.assertThat(exported, containsString("application_timer1_max_seconds 10800.0"));
}
 
Example 4
/**
 * Given a Timer with unit=MINUTES,
 * check that the statistics from JsonExporter will be presented in MINUTES.
 */
@Test
public void timer_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("timer1")
            .withType(MetricType.TIMER)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Timer metric = registry.timer(metadata);
    metric.update(Duration.ofHours(1));
    metric.update(Duration.ofHours(2));
    metric.update(Duration.ofHours(3));

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("timer1");
    assertEquals(120.0, json.getJsonNumber("p50").doubleValue(), 0.001);
    assertEquals(120.0, json.getJsonNumber("mean").doubleValue(), 0.001);
    assertEquals(60.0, json.getJsonNumber("min").doubleValue(), 0.001);
    assertEquals(180.0, json.getJsonNumber("max").doubleValue(), 0.001);
    assertEquals(360.0, json.getJsonNumber("elapsedTime").doubleValue(), 0.001);
}
 
Example 5
/**
 * Given a Histogram with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be presented in SECONDS.
 */
@Test
public void histogram_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("histogram1")
            .withType(MetricType.HISTOGRAM)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Histogram metric = registry.histogram(metadata);
    metric.update(30);
    metric.update(40);
    metric.update(50);

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

    Assert.assertThat(exported, containsString("application_histogram1_min_seconds 1800.0"));
    Assert.assertThat(exported, containsString("application_histogram1_max_seconds 3000.0"));
    Assert.assertThat(exported, containsString("application_histogram1_mean_seconds 2400.0"));
    Assert.assertThat(exported, containsString("application_histogram1_seconds{quantile=\"0.5\"} 2400.0"));
}
 
Example 6
/**
 * Given a Histogram with unit=MINUTES,
 * check that the statistics from JsonExporter will be presented in MINUTES.
 */
@Test
public void histogram_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("timer1")
            .withType(MetricType.TIMER)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Timer metric = registry.timer(metadata);
    metric.update(Duration.ofHours(1));
    metric.update(Duration.ofHours(2));
    metric.update(Duration.ofHours(3));

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("timer1");
    assertEquals(120.0, json.getJsonNumber("p50").doubleValue(), 0.001);
    assertEquals(120.0, json.getJsonNumber("mean").doubleValue(), 0.001);
    assertEquals(60.0, json.getJsonNumber("min").doubleValue(), 0.001);
    assertEquals(180.0, json.getJsonNumber("max").doubleValue(), 0.001);
}
 
Example 7
/**
 * Given a Gauge with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be presented in SECONDS.
 */
@Test
public void gauge_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("gauge1")
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Gauge<Long> gaugeInstance = () -> 3L;
    registry.register(metadata, gaugeInstance);

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

    Assert.assertThat(exported, containsString("application_gauge1_seconds 180.0"));
}
 
Example 8
/**
 * Given a Gauge with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be presented in MINUTES.
 */
@Test
public void gauge_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("gauge1")
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Gauge<Long> gaugeInstance = () -> 3L;
    registry.register(metadata, gaugeInstance);

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject();
    assertEquals(3, json.getInt("gauge1"));
}
 
Example 9
Source Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: Apache License 2.0 6 votes vote down vote up
private void runtimeMetrics(MetricRegistry registry) {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    Metadata meta = Metadata.builder()
            .withName(JVM_UPTIME)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.MILLISECONDS)
            .withDisplayName("JVM Uptime")
            .withDescription("Displays the time from the start of the Java virtual machine in milliseconds.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return runtimeMXBean.getUptime();
        }
    });
}
 
Example 10
Source Project: quarkus   Source File: QuarkusJaxRsMetricsFilter.java    License: Apache License 2.0 6 votes vote down vote up
private void finishRequest(Long start, Class<?> resourceClass, Method resourceMethod) {
    long value = System.nanoTime() - start;
    MetricID metricID = getMetricID(resourceClass, resourceMethod);

    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.BASE);
    if (!registry.getMetadata().containsKey(metricID.getName())) {
        // if no metric with this name exists yet, register it
        Metadata metadata = Metadata.builder()
                .withName(metricID.getName())
                .withDescription(
                        "The number of invocations and total response time of this RESTful resource method since the start of the server.")
                .withUnit(MetricUnits.NANOSECONDS)
                .build();
        registry.simpleTimer(metadata, metricID.getTagsAsArray());
    }
    registry.simpleTimer(metricID.getName(), metricID.getTagsAsArray())
            .update(Duration.ofNanos(value));
}
 
Example 11
Source Project: microprofile-metrics   Source File: MetricAppBean.java    License: Apache License 2.0 6 votes vote down vote up
public void histogramMe() {

        Metadata metadata = Metadata.builder().withName("metricTest.test1.histogram")
                .withType(MetricType.HISTOGRAM).withUnit(MetricUnits.BYTES).build();
        Histogram histogram = metrics.histogram(metadata);

        // Go both ways to minimize error due to decay
        for (int i = 0; i < 500; i++) {
            histogram.update(i);
            histogram.update(999 - i);
        }

        Metadata metadata2 = Metadata.builder().withName("metricTest.test1.histogram2")
                .withType(MetricType.HISTOGRAM).withUnit(MetricUnits.NONE).build();
        Histogram histogram2 = metrics.histogram(metadata2);
        histogram2.update(1);
    }
 
Example 12
@Counted(unit = MetricUnits.NONE,
        name = "getBook",
        absolute = true,
        monotonic = true,
        displayName = "get single book",
        description = "Monitor how many times getBook method was called")
@GET
@Path("{id}")
public Response getBook(@PathParam("id") Long id) {
    Book book = bookService.findById(id);

    return Response.ok(book).build();
}
 
Example 13
@Metered(name = "create-books",
        unit = MetricUnits.MILLISECONDS,
        description = "Monitor the rate events occured",
        absolute = true)
@POST
public Response create(Book book) {
    bookService.create(book);
    return Response.ok().build();
}
 
Example 14
Source Project: quarkus-deep-dive   Source File: TodoResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Counted(name = "getAllCount", monotonic = true,
        description = "How many getAll calls have been done.")
@Timed(name = "getAllTime",
        description = "How long does the getAll method takes.",
        unit = MetricUnits.MILLISECONDS)
public List<Todo> getAll() {
    return Todo.listAll(Sort.by("order"));
}
 
Example 15
Source Project: quarkus-deep-dive   Source File: TodoResource.java    License: Apache License 2.0 5 votes vote down vote up
@POST
@Transactional
@Counted(name = "createCount", monotonic = true, description = "How many create calls have been done.")
@Timed(name = "createTime", description = "How long does the create method takes.", unit = MetricUnits.MILLISECONDS)
public Response create(@Valid Todo item) {
    item.persist();
    return Response.status(Status.CREATED).entity(item).build();
}
 
Example 16
Source Project: quarkus-deep-dive   Source File: TodoResource.java    License: Apache License 2.0 5 votes vote down vote up
@DELETE
@Transactional
@Counted(name = "deleteCompletedCount", monotonic = true, description = "How many deleteCompleted calls have been done.")
@Timed(name = "deleteCompletedTime", description = "How long does the deleteCompleted method takes.", unit = MetricUnits.MILLISECONDS)
public Response deleteCompleted() {
    Todo.deleteCompleted();
    return Response.noContent().build();
}
 
Example 17
Source Project: quarkus-deep-dive   Source File: TodoResource.java    License: Apache License 2.0 5 votes vote down vote up
@DELETE
@Transactional
@Path("/{id}")
@Counted(name = "deleteOneCount", monotonic = true, description = "How many deleteOne calls have been done.")
@Timed(name = "deleteOneTime", description = "How long does the deleteOne method takes.", unit = MetricUnits.MILLISECONDS)
public Response deleteOne(@PathParam("id") Long id) {
    Todo entity = Todo.findById(id);
    if (entity == null) {
        throw new WebApplicationException("Todo with id of " + id + " does not exist.", Status.NOT_FOUND);
    }
    entity.delete();
    return Response.noContent().build();
}
 
Example 18
Source Project: quarkus-quickstarts   Source File: PrimeNumberChecker.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{number}")
@Produces("text/plain")
@Counted(name = "performedChecks", description = "How many primality checks have been performed.")
@Timed(name = "checksTimer", description = "A measure how long it takes to perform the primality test.", unit = MetricUnits.MILLISECONDS)
public String checkIfPrime(@PathParam long number) {
    if (number < 1) {
        return "Only natural numbers can be prime numbers.";
    }
    if (number == 1) {
        return "1 is not prime.";
    }
    if (number == 2) {
        return "2 is prime.";
    }
    if (number % 2 == 0) {
        return number + " is not prime, it is divisible by 2.";
    }
    for (int i = 3; i < Math.floor(Math.sqrt(number)) + 1; i = i + 2) {
        if (number % i == 0) {
            return number + " is not prime, is divisible by " + i + ".";
        }
    }
    if (number > highestPrimeNumberSoFar) {
        highestPrimeNumberSoFar = number;
    }
    return number + " is prime.";
}
 
Example 19
Source Project: smallrye-metrics   Source File: ExporterUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Double convertNanosTo(Double value, String unit) {

        Double out;

        switch (unit) {
            case MetricUnits.NANOSECONDS:
                out = value;
                break;
            case MetricUnits.MICROSECONDS:
                out = value / NANOS_PER_MICROSECOND;
                break;
            case MetricUnits.MILLISECONDS:
                out = value / NANOS_PER_MILLI;
                break;
            case MetricUnits.SECONDS:
                out = value / NANOS_PER_SECOND;
                break;
            case MetricUnits.MINUTES:
                out = value / NANOS_PER_MINUTE;
                break;
            case MetricUnits.HOURS:
                out = value / NANOS_PER_HOUR;
                break;
            case MetricUnits.DAYS:
                out = value / NANOS_PER_DAY;
                break;
            default:
                out = value;
        }
        return out;
    }
 
Example 20
Source Project: smallrye-metrics   Source File: ReusabilityByDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentGauge() {
    Metadata metadata = Metadata.builder().withName("mycgauge").withUnit(MetricUnits.SECONDS).build();
    try {
        registry.concurrentGauge(metadata).inc();
        registry.concurrentGauge(metadata).inc();
        assertEquals(2, registry.concurrentGauge("mycgauge").getCount());
    } finally {
        registry.concurrentGauge(metadata).dec();
        registry.concurrentGauge(metadata).dec();
    }
}
 
Example 21
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleTimers() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = new MetadataBuilder()
            .withUnit(MetricUnits.SECONDS)
            .withName("mysimpletimer")
            .build();

    SimpleTimer timerWithoutTags = registry.simpleTimer(metadata);
    SimpleTimer timerRed = registry.simpleTimer(metadata, new Tag("color", "red"));
    SimpleTimer timerBlue = registry.simpleTimer(metadata, new Tag("color", "blue"), new Tag("foo", "bar"));

    timerWithoutTags.update(Duration.ofSeconds(1));
    timerRed.update(Duration.ofSeconds(2));
    timerBlue.update(Duration.ofSeconds(3));
    timerBlue.update(Duration.ofSeconds(4));

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

    JsonObject mytimerObject = json.getJsonObject("mysimpletimer");

    assertEquals(1.0, mytimerObject.getJsonNumber("count").doubleValue(), 1e-10);
    assertEquals(1.0, mytimerObject.getJsonNumber("count;color=red").doubleValue(), 1e-10);
    assertEquals(2.0, mytimerObject.getJsonNumber("count;color=blue;foo=bar").doubleValue(), 1e-10);

    assertEquals(1.0, mytimerObject.getJsonNumber("elapsedTime").doubleValue(), 1e-10);
    assertEquals(2.0, mytimerObject.getJsonNumber("elapsedTime;color=red").doubleValue(), 1e-10);
    assertEquals(7.0, mytimerObject.getJsonNumber("elapsedTime;color=blue;foo=bar").doubleValue(), 1e-10);
}
 
Example 22
@Test
public void testFindBaseUnit1() {
    String foo = MetricUnits.HOURS;
    String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
    assertEquals(MetricUnits.SECONDS, out);
    String promUnit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(out));
    assertEquals("seconds", promUnit);
}
 
Example 23
@Test
public void testFindBaseUnit2() {
    String foo = MetricUnits.MILLISECONDS;
    String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
    assertEquals(MetricUnits.SECONDS, out);
    String promUnit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(out));
    assertEquals("seconds", promUnit);
}
 
Example 24
Source Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Mimics Uptime metrics from Micrometer. Most of the logic here is basically copied from
 * {@link <a href=
 * "https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java">Micrometer
 * Uptime metrics</a>}.
 * 
 * @param registry
 */
private void micrometerRuntimeMetrics(MetricRegistry registry) {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.runtime")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("The uptime of the Java virtual machine")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getUptime();
                }
            });
    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.start.time")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("Start time of the process since unix epoch.")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getStartTime();
                }
            });
}
 
Example 25
Source Project: quarkus   Source File: MetadataHolder.java    License: Apache License 2.0 5 votes vote down vote up
public static MetadataHolder from(Metadata metadata) {
    MetadataHolder result = new MetadataHolder();
    result.name = metadata.getName();
    result.metricType = metadata.getTypeRaw();
    result.description = metadata.getDescription().orElse(null);
    result.displayName = metadata.getDisplayName();
    result.unit = metadata.getUnit().orElse(MetricUnits.NONE);
    return result;
}
 
Example 26
@Counted(name = "counter")
@Gauge(name = "gauge", unit = MetricUnits.NONE)
@Metered(name = "meter")
@Timed(name = "timer")
public Long metricsMethod() {
    return 1234L;
}
 
Example 27
Source Project: microprofile-metrics   Source File: MetricAppBean.java    License: Apache License 2.0 5 votes vote down vote up
public void gaugeMe() {

        @SuppressWarnings("unchecked")
        Gauge<Long> gauge = (Gauge<Long>) metrics.getGauge(new MetricID("metricTest.test1.gauge"));
        if (gauge == null) {
            gauge = () -> {
                return 19L;
            };

            Metadata metadata = Metadata.builder().withName("metricTest.test1.gauge")
                    .withType(MetricType.GAUGE).withUnit(MetricUnits.GIGABYTES).build();
            metrics.register(metadata, gauge);
        }

    }
 
Example 28
@Test
public void testMetricUnits() throws InterruptedException, ExecutionException {
    // Call the method to ensure that all metrics get registered
    allMetricsBean.doWork().get();
    
    // Validate that each metric has metadata which declares the correct unit
    for (MetricDefinition metric : MetricDefinition.values()) {
        Metadata metadata = metricRegistry.getMetadata().get(metric.getName());
        
        assertNotNull(metadata, "Missing metadata for metric " + metric);
        
        assertEquals(metadata.getUnit().orElse(MetricUnits.NONE), metric.getUnit(), "Incorrect unit for metric " + metric);
    }
}
 
Example 29
Source Project: tomee   Source File: WeatherService.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/day/status")

    @Metered(name = "dailyStatus", unit = MetricUnits.MINUTES, description = "Metrics to daily weather status method", absolute = true)
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String dayStatus() {
        return "Hi, today is a sunny day!";
    }
 
Example 30
Source Project: tomee   Source File: WeatherService.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/week/status")
@Metered(name = "weeklyStatus", unit = MetricUnits.MINUTES, description = "Metrics to weekly weather status method", absolute = true)
@GET
@Produces(MediaType.TEXT_PLAIN)
public String weekStatus() {
    return "Hi, week will be mostly sunny!";
}