Metrics
- Requirements
- Installation
- Brief Overview
- Getting started
- Enable Metrics
- Enable Views
- Exporting stats
- Viewing your metrics
In this quickstart, we’ll glean insights from code segments and learn how to:
- Collect metrics using OpenCensus Metrics and Tags
- Register and enable an exporter for a backend of our choice
- View the metrics on the backend of our choice
Requirements
- Java 8+
- Apache Maven
For assistance setting up Apache Maven, Click here for instructions.
- Prometheus as our choice of metrics backend: we are picking it beause it is free, open source and easy to setup
For assistance setting up Prometheus, Click here for a guided codelab.
You can swap out any other exporter from the list of Java exporters
Installation
We will first create our project directory, add our pom.xml, and our source code.
mkdir repl-app
cd repl-app
touch pom.xml
mkdir -p src/main/java/io/opencensus/metrics/quickstart
touch src/main/java/io/opencensus/metrics/quickstart/Repl.javaPut this in your newly generated pom.xml file:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.opencensus.metrics.quickstart</groupId>
<artifactId>quickstart</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>quickstart</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<opencensus.version>0.15.0</opencensus.version> <!-- The OpenCensus version to use -->
</properties>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<programs>
<program>
<id>Repl</id>
<mainClass>io.opencensus.metrics.quickstart.Repl</mainClass>
</program>
</programs>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>Put this in src/main/java/io/opencensus/metrics/quickstart/Repl.java:
package io.opencensus.metrics.quickstart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Repl {
public static void main(String ...args) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
readEvaluateProcessLine(stdin);
} catch (IOException e) {
System.err.println("Exception "+ e);
}
}
}
private static String processLine(String line) {
return line.toUpperCase();
}
private static void readEvaluateProcessLine(BufferedReader in) throws IOException {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
String processed = processLine(line);
System.out.println("< " + processed + "\n");
}
}To install required dependencies, run this from your project’s root directory:
# Make sure to be in your project's root directory
mvn installBrief Overview
By the end of this tutorial, we will do these four things to obtain metrics using OpenCensus:
- Create quantitative metrics that we will record
- Create tags that we will associate with our metrics
- Organize our metrics, similar to writing a report, in to a
View - Export our views to a backend (Prometheus in this case)
Getting Started
The Repl application takes input from users, converts any lower-case letters into upper-case letters, and echoes the result back to the user, for example:
> foo
< FOOWe will instrument this application to collect metrics, such as:
- Latency per processing loop
- Number of lines read
- Number of errors
- Line lengths
Let’s first run the application and see what we have.
mvn exec:java -Dexec.mainClass=io.opencensus.metrics.quickstart.ReplYou will be given a text prompt. Try typing in a lowercase word and hit enter to receive the uppercase equivalent.
You should see something like this after a few tries:

To exit out of the application, hit ctrl + c on your keyboard.
From here on out, we will be rewriting sections of src/main/java/io/opencensus/metrics/quickstart/Repl.java and pom.xml.
You can recompile and run the application after editing it by running this command:
mvn installEnable Metrics
Import Packages
To enable metrics, we’ll declare the dependencies in your pom.xml file. Add the following snippet of code after the <properties>...</properties> node.
<dependencies>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-api</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-impl</artifactId>
<version>${opencensus.version}</version>
</dependency>
</dependencies><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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.opencensus.metrics.quickstart</groupId>
<artifactId>quickstart</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>quickstart</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<opencensus.version>0.15.0</opencensus.version> <!-- The OpenCensus version to use -->
</properties>
<dependencies>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-api</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-impl</artifactId>
<version>${opencensus.version}</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<programs>
<program>
<id>Repl</id>
<mainClass>io.opencensus.metrics.quickstart.Repl</mainClass>
</program>
</programs>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>We will now be importing modules into src/main/java/io/opencensus/metrics/quickstart/Repl.java. Append the following snippet after the existing import statements:
import io.opencensus.common.Scope;
import io.opencensus.stats.Stats;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Measure.MeasureDouble;
import io.opencensus.stats.Stats;
import io.opencensus.stats.StatsRecorder;
import io.opencensus.stats.View;
import io.opencensus.tags.Tags;
import io.opencensus.tags.Tagger;
import io.opencensus.tags.TagContext;
import io.opencensus.tags.TagContextBuilder;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;Create Measures for Metrics
First, we will create the variables needed to later record our metrics. Place the following snippet on the line after public class Repl {:
// The latency in milliseconds
private static final MeasureDouble M_LATENCY_MS = MeasureDouble.create("repl/latency", "The latency in milliseconds per REPL loop", "ms");
// Counts/groups the lengths of lines read in.
private static final MeasureLong M_LINE_LENGTHS = MeasureLong.create("repl/line_lengths", "The distribution of line lengths", "By");
private static final Tagger tagger = Tags.getTagger();
private static final StatsRecorder statsRecorder = Stats.getStatsRecorder();
private static void recordStat(MeasureLong ml, Long n) {
statsRecorder.newMeasureMap().put(ml, n);
}package io.opencensus.metrics.quickstart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import io.opencensus.common.Scope;
import io.opencensus.stats.Stats;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Measure.MeasureDouble;
import io.opencensus.stats.Stats;
import io.opencensus.stats.StatsRecorder;
import io.opencensus.stats.View;
import io.opencensus.tags.Tags;
import io.opencensus.tags.Tagger;
import io.opencensus.tags.TagContext;
import io.opencensus.tags.TagContextBuilder;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;
public class Repl {
// The latency in milliseconds
private static final MeasureDouble M_LATENCY_MS = MeasureDouble.create("repl/latency", "The latency in milliseconds per REPL loop", "ms");
// Counts/groups the lengths of lines read in.
private static final MeasureLong M_LINE_LENGTHS = MeasureLong.create("repl/line_lengths", "The distribution of line lengths", "By");
private static final Tagger tagger = Tags.getTagger();
private static final StatsRecorder statsRecorder = Stats.getStatsRecorder();
public static void main(String ...args) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
readEvaluateProcessLine(stdin);
} catch (IOException e) {
System.err.println("Exception "+ e);
}
}
}
private static void recordStat(MeasureLong ml, Long n) {
statsRecorder.newMeasureMap().put(ml, n);
}
private static String processLine(String line) {
return line.toUpperCase();
}
private static void readEvaluateProcessLine(BufferedReader in) throws IOException {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
String processed = processLine(line);
System.out.println("< " + processed + "\n");
}
}Create Tags
Now we will create the variable later needed to record extra text meta-data.
Insert the following snippet on the line before private static final Tagger tagger = Tags.getTagger();:
// The tag "method"
private static final TagKey KEY_METHOD = TagKey.create("method");
private static final TagKey KEY_STATUS = TagKey.create("status");
private static final TagKey KEY_ERROR = TagKey.create("error");package io.opencensus.metrics.quickstart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import io.opencensus.common.Scope;
import io.opencensus.stats.Stats;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Measure.MeasureDouble;
import io.opencensus.stats.Stats;
import io.opencensus.stats.StatsRecorder;
import io.opencensus.stats.View;
import io.opencensus.tags.Tags;
import io.opencensus.tags.Tagger;
import io.opencensus.tags.TagContext;
import io.opencensus.tags.TagContextBuilder;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;
public class Repl {
// The latency in milliseconds
private static final MeasureDouble M_LATENCY_MS = MeasureDouble.create("repl/latency", "The latency in milliseconds per REPL loop", "ms");
// Counts/groups the lengths of lines read in.
private static final MeasureLong M_LINE_LENGTHS = MeasureLong.create("repl/line_lengths", "The distribution of line lengths", "By");
// The tag "method"
private static final TagKey KEY_METHOD = TagKey.create("method");
// The tag "status"
private static final TagKey KEY_STATUS = TagKey.create("status");
// The tag "error"
private static final TagKey KEY_ERROR = TagKey.create("error");
private static final Tagger tagger = Tags.getTagger();
private static final StatsRecorder statsRecorder = Stats.getStatsRecorder();
public static void main(String ...args) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
readEvaluateProcessLine(stdin);
} catch (IOException e) {
System.err.println("Exception "+ e);
}
}
}
private static void recordStat(MeasureLong ml, Long n) {
statsRecorder.newMeasureMap().put(ml, n);
}
private static String processLine(String line) {
return line.toUpperCase();
}
private static void readEvaluateProcessLine(BufferedReader in) throws IOException {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
String processed = processLine(line);
System.out.println("< " + processed + "\n");
}
}We will later use this tag, called