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 since 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>8.0.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>4.0.1</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.7.1</version>
 43      <scope>test</scope>
 44    </dependency>
 45    <dependency>
 46      <groupId>org.apache.cxf</groupId>
 47      <artifactId>cxf-rt-rs-client</artifactId>
 48      <version>3.4.3</version>
 49      <scope>test</scope>
 50    </dependency>
 51    <dependency>
 52      <groupId>org.apache.cxf</groupId>
 53      <artifactId>cxf-rt-rs-extension-providers</artifactId>
 54      <version>3.4.3</version>
 55      <scope>test</scope>
 56    </dependency>
 57    <dependency>
 58      <groupId>org.glassfish</groupId>
 59      <artifactId>javax.json</artifactId>
 60      <version>1.1.4</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.1</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.3.4</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>

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <!-- tag::mpMetrics[] -->
 8    <feature>mpMetrics-3.0</feature>
 9    <!-- end::mpMetrics[] -->
10    <feature>mpRestClient-2.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>

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

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, 2020 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 javax.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;
 27import org.eclipse.microprofile.metrics.annotation.SimplyTimed;
 28
 29import io.openliberty.guides.inventory.model.InventoryList;
 30import io.openliberty.guides.inventory.model.SystemData;
 31
 32// tag::ApplicationScoped[]
 33@ApplicationScoped
 34// end::ApplicationScoped[]
 35public class InventoryManager {
 36
 37  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 38  private InventoryUtils invUtils = new InventoryUtils();
 39
 40  // tag::timedForGet[]
 41  // tag::nameForGet[]
 42  @Timed(name = "inventoryProcessingTime",
 43  // end::nameForGet[]
 44         // tag::tagForGet[]
 45         tags = {"method=get"},
 46         // end::tagForGet[]
 47         // tag::absoluteForGet[]
 48         absolute = true,
 49         // end::absoluteForGet[]
 50         // tag::desForGet[]
 51         description = "Time needed to process the inventory")
 52         // end::desForGet[]
 53  // end::timedForGet[]
 54  // tag::get[]
 55  public Properties get(String hostname) {
 56    return invUtils.getProperties(hostname);
 57  }
 58  // end::get[]
 59
 60  // tag::timedForAdd[]
 61  // tag::nameForAdd[]
 62  @SimplyTimed(name = "inventoryAddingTime", 
 63  // end::nameForAdd[]
 64    // tag::absoluteForAdd[]
 65    absolute=true,
 66    // end::absoluteForAdd[]
 67    // tag::desForAdd[]
 68    description = "Time needed to add system properties to the inventory")
 69    // end::desForAdd[]
 70  // end::timedForAdd[]
 71  // tag::add[]
 72  public void add(String hostname, Properties systemProps) {
 73    Properties props = new Properties();
 74    props.setProperty("os.name", systemProps.getProperty("os.name"));
 75    props.setProperty("user.name", systemProps.getProperty("user.name"));
 76
 77    SystemData host = new SystemData(hostname, props);
 78    if (!systems.contains(host))
 79      systems.add(host);
 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 @SimplyTimed 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. @SimplyTimed supports the same fields as @Timed in the previous table.

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>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <!-- tag::mpMetrics[] -->
 8    <feature>mpMetrics-3.0</feature>
 9    <!-- end::mpMetrics[] -->
10    <feature>mpRestClient-2.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

MetricsIT.java

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

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2020 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 javax.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;
 27import org.eclipse.microprofile.metrics.annotation.SimplyTimed;
 28
 29import io.openliberty.guides.inventory.model.InventoryList;
 30import io.openliberty.guides.inventory.model.SystemData;
 31
 32// tag::ApplicationScoped[]
 33@ApplicationScoped
 34// end::ApplicationScoped[]
 35public class InventoryManager {
 36
 37  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 38  private InventoryUtils invUtils = new InventoryUtils();
 39
 40  // tag::timedForGet[]
 41  // tag::nameForGet[]
 42  @Timed(name = "inventoryProcessingTime",
 43  // end::nameForGet[]
 44         // tag::tagForGet[]
 45         tags = {"method=get"},
 46         // end::tagForGet[]
 47         // tag::absoluteForGet[]
 48         absolute = true,
 49         // end::absoluteForGet[]
 50         // tag::desForGet[]
 51         description = "Time needed to process the inventory")
 52         // end::desForGet[]
 53  // end::timedForGet[]
 54  // tag::get[]
 55  public Properties get(String hostname) {
 56    return invUtils.getProperties(hostname);
 57  }
 58  // end::get[]
 59
 60  // tag::timedForAdd[]
 61  // tag::nameForAdd[]
 62  @SimplyTimed(name = "inventoryAddingTime", 
 63  // end::nameForAdd[]
 64    // tag::absoluteForAdd[]
 65    absolute=true,
 66    // end::absoluteForAdd[]
 67    // tag::desForAdd[]
 68    description = "Time needed to add system properties to the inventory")
 69    // end::desForAdd[]
 70  // end::timedForAdd[]
 71  // tag::add[]
 72  public void add(String hostname, Properties systemProps) {
 73    Properties props = new Properties();
 74    props.setProperty("os.name", systemProps.getProperty("os.name"));
 75    props.setProperty("user.name", systemProps.getProperty("user.name"));
 76
 77    SystemData host = new SystemData(hostname, props);
 78    if (!systems.contains(host))
 79      systems.add(host);
 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[]

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 JAX-RS 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
  • 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 testPropertiesAddSimplyTimeMetric() test case validates the @SimplyTimed 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 @SimplyTimed 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. Register this client with a JsrJsonpProvider JSON-P provider to process JSON resources. 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

Copied to clipboard
Copy code block
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