Providing metrics from a microservice

duration 15 minutes

Prerequisites:

You’ll explore how to provide system and application metrics from a microservice with MicroProfile Metrics.

What you’ll learn

You will learn how to use MicroProfile Metrics to provide metrics from a microservice. You can monitor metrics to determine the performance and health of a service. You can also use them to pinpoint issues, collect data for capacity planning, or to decide when to scale a service to run with more or fewer resources.

The application that you will work with is an inventory service that stores information about various systems. The inventory service communicates with the system service on a particular host to retrieve its system properties when necessary.

You will use annotations provided by MicroProfile Metrics to instrument the inventory service to provide application-level metrics data. You will add counter, gauge, and timer metrics to the service.

You will also check well-known REST endpoints that are defined by MicroProfile Metrics to review the metrics data collected. Monitoring agents can access these endpoints to collect metrics.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-metrics.git
cd guide-microprofile-metrics

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

cd finish
mvn liberty:run

After you see the following message, your application server is ready:

The defaultServer server is ready to run a smarter planet.

Point your browser to the http://localhost:9080/inventory/systems URL to access the inventory service. Because you just started the application, the inventory is empty. Access the http://localhost:9080/inventory/systems/localhost URL to add the localhost into the inventory.

Access the inventory service at the http://localhost:9080/inventory/systems URL at least once so that application metrics are collected. Otherwise, the metrics do not appear.

Next, point your browser to the http://localhost:9443/metrics MicroProfile Metrics endpoint. Log in as the admin user with adminpwd as the password. You can see both the system and application metrics in a text format.

To see only the application metrics, point your browser to https://localhost:9443/metrics/application.

See the following sample outputs for the @Timed, @Gauge, and @Counted metrics:

# TYPE application_inventoryProcessingTime_rate_per_second gauge
application_inventoryProcessingTime_rate_per_second{method="get"} 0.0019189661542898407
...
# TYPE application_inventoryProcessingTime_seconds summary
# HELP application_inventoryProcessingTime_seconds Time needed to process the inventory
application_inventoryProcessingTime_seconds_count{method="get"} 1
application_inventoryProcessingTime_seconds{method="get",quantile="0.5"} 0.127965469
...
# TYPE application_inventoryProcessingTime_rate_per_second gauge
application_inventoryProcessingTime_rate_per_second{method="list"} 0.0038379320982686884
...
# TYPE application_inventoryProcessingTime_seconds summary
# HELP application_inventoryProcessingTime_seconds Time needed to process the inventory
application_inventoryProcessingTime_seconds_count{method="list"} 2
application_inventoryProcessingTime_seconds{method="list",quantile="0.5"} 2.2185000000000002E-5
...
# TYPE application_inventorySizeGauge gauge
# HELP application_inventorySizeGauge Number of systems in the inventory
application_inventorySizeGauge 1
# TYPE application_inventoryAccessCount_total counter
# HELP application_inventoryAccessCount_total Number of times the list of systems method is requested
application_inventoryAccessCount_total 1

To see only the system metrics, point your browser to https://localhost:9443/metrics/base.

See the following sample output:

# TYPE base_jvm_uptime_seconds gauge
# HELP base_jvm_uptime_seconds Displays the start time of the Java virtual machine in milliseconds. This attribute displays the approximate time when the Java virtual machine started.
base_jvm_uptime_seconds 30.342000000000002
# TYPE base_classloader_loadedClasses_count gauge
# HELP base_classloader_loadedClasses_count Displays the number of classes that are currently loaded in the Java virtual machine.
base_classloader_loadedClasses_count 11231

To see only the vendor metrics, point your browser to https://localhost:9443/metrics/vendor.

See the following sample output:

# TYPE vendor_threadpool_size gauge
# HELP vendor_threadpool_size The size of the thread pool.
vendor_threadpool_size{pool="Default_Executor"} 32
# TYPE vendor_servlet_request_total counter
# HELP vendor_servlet_request_total The number of visits to this servlet from the start of the server.
vendor_servlet_request_total{servlet="microprofile_metrics_io_openliberty_guides_inventory_InventoryApplication"} 1

After you are finished checking out the application, stop the Open Liberty server by pressing CTRL+C in the command-line session where you ran the server. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Adding MicroProfile Metrics to the inventory service

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3
  4  <modelVersion>4.0.0</modelVersion>
  5
  6  <groupId>io.openliberty.guides</groupId>
  7  <artifactId>guide-microprofile-metrics</artifactId>
  8  <version>1.0-SNAPSHOT</version>
  9  <packaging>war</packaging>
 10
 11  <properties>
 12    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 13    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 14    <maven.compiler.source>1.8</maven.compiler.source>
 15    <maven.compiler.target>1.8</maven.compiler.target>
 16    <!-- Liberty configuration -->
 17    <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 18    <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 19  </properties>
 20
 21  <dependencies>
 22    <!-- Provided dependencies -->
 23    <dependency>
 24      <groupId>jakarta.platform</groupId>
 25      <artifactId>jakarta.jakartaee-api</artifactId>
 26      <version>9.1.0</version>
 27      <scope>provided</scope>
 28    </dependency>
 29    <dependency>
 30      <groupId>org.eclipse.microprofile</groupId>
 31      <!-- tag::microprofile[] -->
 32      <artifactId>microprofile</artifactId>
 33      <!-- end::microprofile[] -->
 34      <version>5.0</version>
 35      <type>pom</type>
 36      <scope>provided</scope>
 37    </dependency>
 38    <!-- For tests -->
 39    <dependency>
 40      <groupId>org.junit.jupiter</groupId>
 41      <artifactId>junit-jupiter</artifactId>
 42      <version>5.8.2</version>
 43      <scope>test</scope>
 44    </dependency>
 45    <dependency>
 46      <groupId>org.jboss.resteasy</groupId>
 47      <artifactId>resteasy-client</artifactId>
 48      <version>6.0.0.Final</version>
 49      <scope>test</scope>
 50    </dependency>
 51    <dependency>
 52      <groupId>org.jboss.resteasy</groupId>
 53      <artifactId>resteasy-json-binding-provider</artifactId>
 54      <version>6.0.0.Final</version>
 55      <scope>test</scope>
 56    </dependency>
 57    <dependency>
 58      <groupId>org.glassfish</groupId>
 59      <artifactId>jakarta.json</artifactId>
 60      <version>2.0.1</version>
 61      <scope>test</scope>
 62    </dependency>
 63    <!-- Java utility classes -->
 64    <dependency>
 65      <groupId>org.apache.commons</groupId>
 66      <artifactId>commons-lang3</artifactId>
 67      <version>3.12.0</version>
 68    </dependency>
 69  </dependencies>
 70
 71  <build>
 72    <finalName>${project.artifactId}</finalName>
 73    <plugins>
 74      <plugin>
 75        <groupId>org.apache.maven.plugins</groupId>
 76        <artifactId>maven-war-plugin</artifactId>
 77        <version>3.3.2</version>
 78      </plugin>
 79      <!-- Plugin to run unit tests -->
 80      <plugin>
 81        <groupId>org.apache.maven.plugins</groupId>
 82        <artifactId>maven-surefire-plugin</artifactId>
 83        <version>2.22.2</version>
 84      </plugin>
 85      <!-- Enable liberty-maven plugin -->
 86      <plugin>
 87        <groupId>io.openliberty.tools</groupId>
 88        <artifactId>liberty-maven-plugin</artifactId>
 89        <version>3.7.1</version>
 90      </plugin>
 91      <!-- Plugin to run functional tests -->
 92      <plugin>
 93        <groupId>org.apache.maven.plugins</groupId>
 94        <artifactId>maven-failsafe-plugin</artifactId>
 95        <version>2.22.2</version>
 96        <configuration>
 97          <systemPropertyVariables>
 98            <http.port>${liberty.var.default.http.port}</http.port>
 99            <https.port>${liberty.var.default.https.port}</https.port>
100            <javax.net.ssl.trustStore>${project.build.directory}/liberty/wlp/usr/servers/defaultServer/resources/security/key.jks</javax.net.ssl.trustStore>
101          </systemPropertyVariables>
102        </configuration>
103      </plugin>
104    </plugins>
105  </build>
106</project>

Navigate to the start directory to begin.

When you run Open Liberty in development mode, known as dev mode, the server listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

After you see the following message, your application server in dev mode is ready:

**************************************************************
*    Liberty is running in dev mode.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

The MicroProfile Metrics API is included in the MicroProfile dependency specified by your pom.xml file. Look for the dependency with the microprofile artifact ID. This dependency provides a library that allows you to use the MicroProfile Metrics API in your code to provide metrics from your microservices.

Replace the server configuration file.
src/main/liberty/config/server.xml

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>restfulWS-3.0</feature>
 5    <feature>jsonp-2.0</feature>
 6    <feature>jsonb-2.0</feature>
 7    <feature>cdi-3.0</feature>
 8    <feature>mpConfig-3.0</feature>
 9   <feature>mpMetrics-4.0</feature>
10   <feature>mpRestClient-3.0</feature>
11 </featureManager>
12
13  <variable name="default.http.port" defaultValue="9080"/>
14  <variable name="default.https.port" defaultValue="9443"/>
15
16  <applicationManager autoExpand="true" />
17  <!-- tag::quickStartSecurity[] -->
18  <quickStartSecurity userName="admin" userPassword="adminpwd"/>
19  <!-- end::quickStartSecurity[] -->
20  <httpEndpoint host="*" httpPort="${default.http.port}"
21      httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
22  <webApplication location="guide-microprofile-metrics.war" contextRoot="/"/>
23</server>

The mpMetrics feature enables MicroProfile Metrics support in Open Liberty. Note that this feature requires SSL and the configuration has been provided for you.

The quickStartSecurity configuration element provides basic security to secure the server. When you visit the /metrics endpoint, use the credentials defined in the server configuration to log in and view the data.

Adding the annotations

Replace the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::InventoryManager[]
 14package io.openliberty.guides.inventory;
 15
 16import java.util.ArrayList;
 17import java.util.Collections;
 18import java.util.List;
 19import java.util.Properties;
 20
 21import jakarta.enterprise.context.ApplicationScoped;
 22
 23import org.eclipse.microprofile.metrics.MetricUnits;
 24import org.eclipse.microprofile.metrics.annotation.Counted;
 25import org.eclipse.microprofile.metrics.annotation.Gauge;
 26import org.eclipse.microprofile.metrics.annotation.Timed;
 27
 28import io.openliberty.guides.inventory.model.InventoryList;
 29import io.openliberty.guides.inventory.model.SystemData;
 30
 31// tag::ApplicationScoped[]
 32@ApplicationScoped
 33// end::ApplicationScoped[]
 34public class InventoryManager {
 35
 36  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 37  private InventoryUtils invUtils = new InventoryUtils();
 38
 39  // tag::timedForGet[]
 40  // tag::nameForGet[]
 41  @Timed(name = "inventoryProcessingTime",
 42  // end::nameForGet[]
 43         // tag::tagForGet[]
 44         tags = {"method=get"},
 45         // end::tagForGet[]
 46         // tag::absoluteForGet[]
 47         absolute = true,
 48         // end::absoluteForGet[]
 49         // tag::desForGet[]
 50         description = "Time needed to process the inventory")
 51         // end::desForGet[]
 52  // end::timedForGet[]
 53  // tag::get[]
 54  public Properties get(String hostname) {
 55    return invUtils.getProperties(hostname);
 56  }
 57  // end::get[]
 58
 59  // tag::timedForAdd[]
 60  // tag::nameForAdd[]
 61  @Timed(name = "inventoryAddingTime",
 62  // end::nameForAdd[]
 63    // tag::absoluteForAdd[]
 64    absolute = true,
 65    // end::absoluteForAdd[]
 66    // tag::desForAdd[]
 67    description = "Time needed to add system properties to the inventory")
 68    // end::desForAdd[]
 69  // end::timedForAdd[]
 70  // tag::add[]
 71  public void add(String hostname, Properties systemProps) {
 72    Properties props = new Properties();
 73    props.setProperty("os.name", systemProps.getProperty("os.name"));
 74    props.setProperty("user.name", systemProps.getProperty("user.name"));
 75
 76    SystemData host = new SystemData(hostname, props);
 77    if (!systems.contains(host)) {
 78      systems.add(host);
 79    }
 80  }
 81  // end::add[]
 82
 83  // tag::timedForList[]
 84  // tag::nameForList[]
 85  @Timed(name = "inventoryProcessingTime",
 86  // end::nameForList[]
 87         // tag::tagForList[]
 88         tags = {"method=list"},
 89         // end::tagForList[]
 90         // tag::absoluteForList[]
 91         absolute = true,
 92         // end::absoluteForList[]
 93         // tag::desForList[]
 94         description = "Time needed to process the inventory")
 95         // end::desForList[]
 96  // end::timedForList[]
 97  // tag::countedForList[]
 98  @Counted(name = "inventoryAccessCount",
 99           absolute = true,
100           description = "Number of times the list of systems method is requested")
101  // end::countedForList[]
102  // tag::list[]
103  public InventoryList list() {
104    return new InventoryList(systems);
105  }
106  // end::list[]
107
108  // tag::gaugeForGetTotal[]
109  // tag::unitForGetTotal[]
110  @Gauge(unit = MetricUnits.NONE,
111  // end::unitForGetTotal[]
112         name = "inventorySizeGauge",
113         absolute = true,
114         description = "Number of systems in the inventory")
115  // end::gaugeForGetTotal[]
116  // tag::getTotal[]
117  public int getTotal() {
118    return systems.size();
119  }
120  // end::getTotal[]
121}
122// end::InventoryManager[]

Apply the @Timed annotation to the get() method, and apply the @Timed annotation to the list() method.

This annotation has these metadata fields:

name

Optional. Use this field to name the metric.

tags

Optional. Use this field to add tags to the metric with the same name.

absolute

Optional. Use this field to determine whether the metric name is the exact name that is specified in the name field or that is specified with the package prefix.

description

Optional. Use this field to describe the purpose of the metric.

The @Timed annotation tracks how frequently the method is invoked and how long it takes for each invocation of the method to complete. Both the get() and list() methods are annotated with the @Timed metric and have the same inventoryProcessingTime name. The method=get and method=list tags add a dimension that uniquely identifies the collected metric data from the inventory processing time in getting the system properties.

  • The method=get tag identifies the inventoryProcessingTime metric that measures the elapsed time to get the system properties when you call the system service.

  • The method=list tag identifies the inventoryProcessingTime metric that measures the elapsed time for the inventory service to list all of the system properties in the inventory.

The tags allow you to query the metrics together or separately based on the functionality of the monitoring tool of your choice. The inventoryProcessingTime metrics for example could be queried to display an aggregate time of both tagged metrics or individual times.

Apply the @Timed annotation to the add() method to track how frequently the method is invoked and how long it takes for each invocation of the method to complete.

Apply the @Counted annotation to the list() method to count how many times the http://localhost:9080/inventory/systems URL is accessed monotonically, which is counting up sequentially.

Apply the @Gauge annotation to the getTotal() method to track the number of systems that are stored in the inventory. When the value of the gauge is retrieved, the underlying getTotal() method is called to return the size of the inventory. Note the additional metadata field:

unit

Set the unit of the metric. If it is MetricUnits.NONE, the metric name is used without appending the unit name, no scaling is applied.

Additional information about these annotations, relevant metadata fields, and more are available at the MicroProfile Metrics Annotation Javadoc.

Enabling vendor metrics for the microservices

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>restfulWS-3.0</feature>
 5    <feature>jsonp-2.0</feature>
 6    <feature>jsonb-2.0</feature>
 7    <feature>cdi-3.0</feature>
 8    <feature>mpConfig-3.0</feature>
 9   <feature>mpMetrics-4.0</feature>
10   <feature>mpRestClient-3.0</feature>
11 </featureManager>
12
13  <variable name="default.http.port" defaultValue="9080"/>
14  <variable name="default.https.port" defaultValue="9443"/>
15
16  <applicationManager autoExpand="true" />
17  <!-- tag::quickStartSecurity[] -->
18  <quickStartSecurity userName="admin" userPassword="adminpwd"/>
19  <!-- end::quickStartSecurity[] -->
20  <httpEndpoint host="*" httpPort="${default.http.port}"
21      httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
22  <webApplication location="guide-microprofile-metrics.war" contextRoot="/"/>
23</server>

MicroProfile Metrics API implementers can provide vendor metrics in the same forms as the base and application metrics do. Open Liberty as a vendor supplies server component metrics when the mpMetrics feature is enabled in the server.xml configuration file.

You can see the vendor-only metrics in the metrics/vendor endpoint. You see metrics from the runtime components, such as Web Application, ThreadPool and Session Management. Note that these metrics are specific to the Liberty application server. Different vendors may provide other metrics. Visit the Metrics reference list for more information.

Building and running the application

The Open Liberty server was started in development mode at the beginning of the guide and all the changes were automatically picked up.

Point your browser to the https://localhost:9443/metrics URL to review all the metrics that are enabled through MicroProfile Metrics. Log in with admin as your username and adminpwd as your password. You see only the system and vendor metrics because the server just started, and the inventory service has not been accessed.

Next, point your browser to the http://localhost:9080/inventory/systems URL. Reload the https://localhost:9443/metrics URL, or access only the application metrics at the https://localhost:9443/metrics/application URL.

You can see the system metrics in the https://localhost:9443/metrics/base URL as well as see the vendor metrics in the https://localhost:9443/metrics/vendor URL.

Testing the metrics

You can test your application manually, but automated tests ensure code quality because they trigger a failure whenever a code change introduces a defect. JUnit and the Jakarta Restful Web Services Client API provide a simple environment for you to write tests.

Create the MetricsIT class.
src/test/java/it/io/openliberty/guides/metrics/MetricsIT.java

MetricsIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::MetricsTest[]
 14package it.io.openliberty.guides.metrics;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17import static org.junit.jupiter.api.Assertions.assertTrue;
 18import static org.junit.jupiter.api.Assertions.fail;
 19
 20import java.io.BufferedReader;
 21import java.io.FileInputStream;
 22import java.io.IOException;
 23import java.io.InputStream;
 24import java.io.InputStreamReader;
 25import java.security.KeyStore;
 26import java.util.ArrayList;
 27import java.util.HashMap;
 28import java.util.List;
 29import java.util.Map;
 30import java.util.Properties;
 31
 32import jakarta.ws.rs.client.Client;
 33import jakarta.ws.rs.client.ClientBuilder;
 34import jakarta.ws.rs.core.MediaType;
 35import jakarta.ws.rs.core.Response;
 36
 37import org.junit.jupiter.api.AfterEach;
 38import org.junit.jupiter.api.BeforeAll;
 39import org.junit.jupiter.api.BeforeEach;
 40import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 41import org.junit.jupiter.api.Order;
 42import org.junit.jupiter.api.Test;
 43import org.junit.jupiter.api.TestMethodOrder;
 44
 45// tag::TestMethodOrder[]
 46@TestMethodOrder(OrderAnnotation.class)
 47// end::TestMethodOrder[]
 48public class MetricsIT {
 49
 50  private static final String KEYSTORE_PATH = System.getProperty("user.dir")
 51                              + "/target/liberty/wlp/usr/servers/"
 52                              + "defaultServer/resources/security/key.p12";
 53  private static final String SYSTEM_ENV_PATH =  System.getProperty("user.dir")
 54                              + "/target/liberty/wlp/usr/servers/"
 55                              + "defaultServer/server.env";
 56
 57  private static String httpPort;
 58  private static String httpsPort;
 59  private static String baseHttpUrl;
 60  private static String baseHttpsUrl;
 61  private static KeyStore keystore;
 62
 63  private List<String> metrics;
 64  private Client client;
 65
 66  private final String INVENTORY_HOSTS = "inventory/systems";
 67  private final String INVENTORY_HOSTNAME = "inventory/systems/localhost";
 68  private final String METRICS_APPLICATION = "metrics/application";
 69
 70  // tag::BeforeAll[]
 71  @BeforeAll
 72  // end::BeforeAll[]
 73  // tag::oneTimeSetup[]
 74  public static void oneTimeSetup() throws Exception {
 75    httpPort = System.getProperty("http.port");
 76    httpsPort = System.getProperty("https.port");
 77    baseHttpUrl = "http://localhost:" + httpPort + "/";
 78    baseHttpsUrl = "https://localhost:" + httpsPort + "/";
 79    loadKeystore();
 80  }
 81  // end::oneTimeSetup[]
 82
 83  private static void loadKeystore() throws Exception {
 84    Properties sysEnv = new Properties();
 85    sysEnv.load(new FileInputStream(SYSTEM_ENV_PATH));
 86    char[] password = sysEnv.getProperty("keystore_password").toCharArray();
 87    keystore = KeyStore.getInstance("PKCS12");
 88    keystore.load(new FileInputStream(KEYSTORE_PATH), password);
 89  }
 90
 91  // tag::BeforeEach[]
 92  @BeforeEach
 93  // end::BeforeEach[]
 94  // tag::setup[]
 95  public void setup() {
 96    client = ClientBuilder.newBuilder().trustStore(keystore).build();
 97  }
 98  // end::setup[]
 99
100  // tag::AfterEach[]
101  @AfterEach
102  // end::AfterEach[]
103  // tag::teardown[]
104  public void teardown() {
105    client.close();
106  }
107  // end::teardown[]
108
109  // tag::Test1[]
110  @Test
111  // end::Test1[]
112  // tag::Order1[]
113  @Order(1)
114  // end::Order1[]
115  // tag::testPropertiesRequestTimeMetric[]
116  public void testPropertiesRequestTimeMetric() {
117    connectToEndpoint(baseHttpUrl + INVENTORY_HOSTNAME);
118    metrics = getMetrics();
119    for (String metric : metrics) {
120      if (metric.startsWith(
121          "application_inventoryProcessingTime_rate_per_second")) {
122        float seconds = Float.parseFloat(metric.split(" ")[1]);
123        assertTrue(4 > seconds);
124      }
125    }
126  }
127  // end::testPropertiesRequestTimeMetric[]
128
129  // tag::Test2[]
130  @Test
131  // end::Test2[]
132  // tag::Order2[]
133  @Order(2)
134  // end::Order2[]
135  // tag::testInventoryAccessCountMetric[]
136  public void testInventoryAccessCountMetric() {
137    metrics = getMetrics();
138    Map<String, Integer> accessCountsBefore = getIntMetrics(metrics,
139            "application_inventoryAccessCount_total");
140    connectToEndpoint(baseHttpUrl + INVENTORY_HOSTS);
141    metrics = getMetrics();
142    Map<String, Integer> accessCountsAfter = getIntMetrics(metrics,
143            "application_inventoryAccessCount_total");
144    for (String key : accessCountsBefore.keySet()) {
145      Integer accessCountBefore = accessCountsBefore.get(key);
146      Integer accessCountAfter = accessCountsAfter.get(key);
147      assertTrue(accessCountAfter > accessCountBefore);
148    }
149  }
150  // end::testInventoryAccessCountMetric[]
151
152  // tag::Test3[]
153  @Test
154  // end::Test3[]
155  // tag::Order3[]
156  @Order(3)
157  // end::Order3[]
158  // tag::testInventorySizeGaugeMetric[]
159  public void testInventorySizeGaugeMetric() {
160    metrics = getMetrics();
161    Map<String, Integer> inventorySizeGauges = getIntMetrics(metrics,
162            "application_inventorySizeGauge");
163    for (Integer value : inventorySizeGauges.values()) {
164      assertTrue(1 <= value);
165    }
166  }
167  // end::testInventorySizeGaugeMetric[]
168
169  // tag::Test4[]
170  @Test
171  // end::Test4[]
172  // tag::Order4[]
173  @Order(4)
174  // end::Order4[]
175  // tag::testPropertiesAddTimeMetric[]
176  public void testPropertiesAddTimeMetric() {
177    connectToEndpoint(baseHttpUrl + INVENTORY_HOSTNAME);
178    metrics = getMetrics();
179    boolean checkMetric = false;
180    for (String metric : metrics) {
181      if (metric.startsWith(
182          "application_inventoryAddingTime_seconds_count")) {
183            checkMetric = true;
184      }
185    }
186    assertTrue(checkMetric);
187  }
188  // end::testPropertiesAddTimeMetric[]
189
190  public void connectToEndpoint(String url) {
191    Response response = this.getResponse(url);
192    this.assertResponse(url, response);
193    response.close();
194  }
195
196  private List<String> getMetrics() {
197    String usernameAndPassword = "admin" + ":" + "adminpwd";
198    String authorizationHeaderValue = "Basic "
199        + java.util.Base64.getEncoder()
200                          .encodeToString(usernameAndPassword.getBytes());
201    Response metricsResponse = client.target(baseHttpsUrl + METRICS_APPLICATION)
202                                     .request(MediaType.TEXT_PLAIN)
203                                     .header("Authorization",
204                                         authorizationHeaderValue)
205                                     .get();
206
207    BufferedReader br = new BufferedReader(new InputStreamReader((InputStream)
208    metricsResponse.getEntity()));
209    List<String> result = new ArrayList<String>();
210    try {
211      String input;
212      while ((input = br.readLine()) != null) {
213        result.add(input);
214      }
215      br.close();
216    } catch (IOException e) {
217      e.printStackTrace();
218      fail();
219    }
220
221    metricsResponse.close();
222    return result;
223  }
224
225  private Response getResponse(String url) {
226    return client.target(url).request().get();
227  }
228
229  private void assertResponse(String url, Response response) {
230    assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
231  }
232
233  private Map<String, Integer> getIntMetrics(List<String> metrics, String metricName) {
234    Map<String, Integer> output = new HashMap<String, Integer>();
235    for (String metric : metrics) {
236      if (metric.startsWith(metricName)) {
237        String[] mSplit = metric.split(" ");
238        String key = mSplit[0];
239        Integer value = Integer.parseInt(mSplit[mSplit.length - 1]);
240        output.put(key, value);
241      }
242    }
243    return output;
244  }
245}
246// end::MetricsTest[]

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::InventoryManager[]
 14package io.openliberty.guides.inventory;
 15
 16import java.util.ArrayList;
 17import java.util.Collections;
 18import java.util.List;
 19import java.util.Properties;
 20
 21import jakarta.enterprise.context.ApplicationScoped;
 22
 23import org.eclipse.microprofile.metrics.MetricUnits;
 24import org.eclipse.microprofile.metrics.annotation.Counted;
 25import org.eclipse.microprofile.metrics.annotation.Gauge;
 26import org.eclipse.microprofile.metrics.annotation.Timed;
 27
 28import io.openliberty.guides.inventory.model.InventoryList;
 29import io.openliberty.guides.inventory.model.SystemData;
 30
 31// tag::ApplicationScoped[]
 32@ApplicationScoped
 33// end::ApplicationScoped[]
 34public class InventoryManager {
 35
 36  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 37  private InventoryUtils invUtils = new InventoryUtils();
 38
 39  // tag::timedForGet[]
 40  // tag::nameForGet[]
 41  @Timed(name = "inventoryProcessingTime",
 42  // end::nameForGet[]
 43         // tag::tagForGet[]
 44         tags = {"method=get"},
 45         // end::tagForGet[]
 46         // tag::absoluteForGet[]
 47         absolute = true,
 48         // end::absoluteForGet[]
 49         // tag::desForGet[]
 50         description = "Time needed to process the inventory")
 51         // end::desForGet[]
 52  // end::timedForGet[]
 53  // tag::get[]
 54  public Properties get(String hostname) {
 55    return invUtils.getProperties(hostname);
 56  }
 57  // end::get[]
 58
 59  // tag::timedForAdd[]
 60  // tag::nameForAdd[]
 61  @Timed(name = "inventoryAddingTime",
 62  // end::nameForAdd[]
 63    // tag::absoluteForAdd[]
 64    absolute = true,
 65    // end::absoluteForAdd[]
 66    // tag::desForAdd[]
 67    description = "Time needed to add system properties to the inventory")
 68    // end::desForAdd[]
 69  // end::timedForAdd[]
 70  // tag::add[]
 71  public void add(String hostname, Properties systemProps) {
 72    Properties props = new Properties();
 73    props.setProperty("os.name", systemProps.getProperty("os.name"));
 74    props.setProperty("user.name", systemProps.getProperty("user.name"));
 75
 76    SystemData host = new SystemData(hostname, props);
 77    if (!systems.contains(host)) {
 78      systems.add(host);
 79    }
 80  }
 81  // end::add[]
 82
 83  // tag::timedForList[]
 84  // tag::nameForList[]
 85  @Timed(name = "inventoryProcessingTime",
 86  // end::nameForList[]
 87         // tag::tagForList[]
 88         tags = {"method=list"},
 89         // end::tagForList[]
 90         // tag::absoluteForList[]
 91         absolute = true,
 92         // end::absoluteForList[]
 93         // tag::desForList[]
 94         description = "Time needed to process the inventory")
 95         // end::desForList[]
 96  // end::timedForList[]
 97  // tag::countedForList[]
 98  @Counted(name = "inventoryAccessCount",
 99           absolute = true,
100           description = "Number of times the list of systems method is requested")
101  // end::countedForList[]
102  // tag::list[]
103  public InventoryList list() {
104    return new InventoryList(systems);
105  }
106  // end::list[]
107
108  // tag::gaugeForGetTotal[]
109  // tag::unitForGetTotal[]
110  @Gauge(unit = MetricUnits.NONE,
111  // end::unitForGetTotal[]
112         name = "inventorySizeGauge",
113         absolute = true,
114         description = "Number of systems in the inventory")
115  // end::gaugeForGetTotal[]
116  // tag::getTotal[]
117  public int getTotal() {
118    return systems.size();
119  }
120  // end::getTotal[]
121}
122// end::InventoryManager[]
  • The testPropertiesRequestTimeMetric() test case validates the @Timed metric. The test case sends a request to the http://localhost:9080/inventory/systems/localhost URL to access the inventory service, which adds the localhost host to the inventory. Next, the test case makes a connection to the https://localhost:9443/metrics/application URL to retrieve application metrics as plain text. Then, it asserts whether the time that is needed to retrieve the system properties for localhost is less than 4 seconds.

  • The testInventoryAccessCountMetric() test case validates the @Counted metric. The test case obtains metric data before and after a request to the http://localhost:9080/inventory/systems URL. It then asserts that the metric was increased after the URL was accessed.

  • The testInventorySizeGaugeMetric() test case validates the @Gauge metric. The test case first ensures that the localhost is in the inventory, then looks for the @Gauge metric and asserts that the inventory size is greater or equal to 1.

  • The testPropertiesAddTimeMetric() test case validates the @Timed metric. The test case sends a request to the http://localhost:9080/inventory/systems/localhost URL to access the inventory service, which adds the localhost host to the inventory. Next, the test case makes a connection to the https://localhost:9443/metrics/application URL to retrieve application metrics as plain text. Then, it looks for the @Timed metric and asserts true if the metric exists.

The oneTimeSetup() method retrieves the port number for the server and builds a base URL string to set up the tests. Apply the @BeforeAll annotation to this method to run it before any of the test cases.

The setup() method creates a JAX-RS client that makes HTTP requests to the inventory service. The teardown() method destroys this client instance. Apply the @BeforeEach annotation so that a method runs before a test case and apply the @AfterEach annotation so that a method runs after a test case. Apply these annotations to methods that are generally used to perform any setup and teardown tasks before and after a test.

To force these test cases to run in a particular order, annotate your MetricsIT test class with the @TestMethodOrder(OrderAnnotation.class) annotation. OrderAnnotation.class runs test methods in numerical order, according to the values specified in the @Order annotation. You can also create a custom MethodOrderer class or use built-in MethodOrderer implementations, such as OrderAnnotation.class, Alphanumeric.class, or Random.class. Label your test cases with the @Test annotation so that they automatically run when your test class runs.

In addition, the endpoint tests src/test/java/it/io/openliberty/guides/inventory/InventoryEndpointIT.java and src/test/java/it/io/openliberty/guides/system/SystemEndpointIT.java are provided for you to test the basic functionality of the inventory and system services. If a test failure occurs, then you might have introduced a bug into the code.

Running the tests

Because you started Open Liberty in development mode at the start of the guide, press the enter/return key to run the tests and see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.4 sec - in it.io.openliberty.guides.system.SystemEndpointIT
Running it.io.openliberty.guides.metrics.MetricsIT
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.476 sec - in it.io.openliberty.guides.metrics.MetricsIT
Running it.io.openliberty.guides.inventory.InventoryEndpointIT
[WARNING ] Interceptor for {http://client.inventory.guides.openliberty.io/}SystemClient has thrown exception, unwinding now
Could not send Message.
[err] The specified host is unknown.
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.264 sec - in it.io.openliberty.guides.inventory.InventoryEndpointIT

Results :

Tests run: 8, Failures: 0, Errors: 0, Skipped: 0

The warning and error messages are expected and result from a request to a bad or an unknown hostname. This request is made in the testUnknownHost() test from the InventoryEndpointIT integration test.

To determine whether the tests detect a failure, go to the MetricsIT.java file and change any of the assertions in the test methods. Then re-run the tests to see a test failure occur.

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Great work! You’re done!

You learned how to enable system, application and vendor metrics for microservices by using MicroProfile Metrics and wrote tests to validate them in Open Liberty.

Guide Attribution

Providing metrics from a microservice by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star