Stackify is now BMC. Read theBlog

Using Java and OpenTelemetry Together

By: Stackify Team
  |  September 24, 2024
Using Java and OpenTelemetry Together

Ensuring your applications are reliable and performant is more critical now than ever. This need has driven the rise of observability practices, where developers and operations teams closely monitor their applications’ health, performance, and behavior. This is where OpenTelemetry (OTel) comes into play.

OpenTelemetry is an open-source project that provides a unified set of APIs, libraries, and agents to capture distributed traces and metrics from your applications. The Cloud Native Computing Foundation (CNCF) project originated from the merger of two observability projects: OpenTracing and OpenCensus. OpenTelemetry aims to standardize how telemetry data—metrics, logs, and traces—are collected and transmitted to monitoring and observability platforms.

Using OpenTelemetry, you can instrument your code to automatically capture data, which can then be sent to various backend systems for analysis and visualization. OpenTelemetry is ideal for gaining insights into your applications that run across distributed systems or microservices architectures.

Why Integrate OpenTelemetry with Java?

Java remains one of the world’s most widely used programming languages, powering a vast array of enterprise applications. These applications often run in complex environments with numerous dependencies, making maintaining high levels of observability challenging. Integrating OpenTelemetry with Java becomes highly beneficial and offers several key advantages:

  1. Improved Observability: OTel tracks requests, identifies bottlenecks, and monitors system performance across multiple services, giving you deep insights into your Java applications
  2. Standardization: OpenTelemetry provides a consistent approach to capturing telemetry data, simplifying the integration of multiple tools and platforms
  3. Flexibility: OpenTelemetry supports many backends, allowing you to choose the monitoring or observability solution that best fits your needs
  4. Ease of Use: Java developers can leverage OpenTelemetry’s extensive documentation and community support to quickly instrument their code without reinventing the wheel

With OpenTelemetry, you gain the ability to monitor and trace every aspect of your Java application, making it easier to identify and resolve issues, optimize performance, and deliver a better user experience.

How Java and OpenTelemetry Work Together

To understand how Java and OpenTelemetry work together, you need to break down the key steps involved in implementing OpenTelemetry in a Java application. The process involves:

  • Setting up the necessary prerequisites
  • Configuring OpenTelemetry
  • Instrumenting your code
  • Exporting the collected telemetry data

Implementing OpenTelemetry with JavaPrerequisites and Setup

Before integrating OpenTelemetry with your Java application, you need to ensure you have the necessary tools and libraries in place. The following prerequisites are essential:

  1. Java Development Kit (JDK): Ensure you have JDK 8 or later installed on your development environment
  2. Maven or Gradle: These build tools are necessary for managing dependencies in your Java project
  3. OpenTelemetry Java SDK: The OpenTelemetry Java SDK provides the core libraries and APIs for instrumenting your applications. You can add this SDK to your project using Maven or Gradle

Here’s how you can add OpenTelemetry to your project using Maven:

<dependency>
    <groupId>io.opentelemetry</groupId>
    <artifactId>opentelemetry-api</artifactId>
    <version>1.10.0</version>
</dependency>
<dependency>
    <groupId>io.opentelemetry</groupId>
    <artifactId>opentelemetry-sdk</artifactId>
    <version>1.10.0</version>
</dependency>

For Gradle, the equivalent dependencies would look like this:

implementation 'io.opentelemetry:opentelemetry-api:1.10.0'
implementation 'io.opentelemetry:opentelemetry-sdk:1.10.0'

Configuration

Once you have the necessary dependencies set up, the next step is to configure OpenTelemetry in your Java application. OpenTelemetry offers a highly flexible configuration system that allows you to customize how telemetry data is collected and exported.

Typically, you will need to configure the following components:

  • Tracer: Responsible for generating trace data
  • Meter: Used for capturing metrics
  • Exporter: Handles the transmission of telemetry data to your chosen backend (e.g., Jaeger, Prometheus, or the Stackify APM)[MS3] Otel Agent

Here’s a basic example of setting up a tracer in your Java application:

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter;

public class OpenTelemetryExample {
    private static final Tracer tracer = OpenTelemetry.getGlobalTracer("example-tracer");

    public static void main(String[] args) {
        // Set up Jaeger exporter
        JaegerGrpcSpanExporter jaegerExporter = JaegerGrpcSpanExporter.builder()
                .setEndpoint("http://localhost:14250")
                .build();

        SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
                .addSpanProcessor(SimpleSpanProcessor.create(jaegerExporter))
                .build();

        OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build();

        // Create a span
        Span span = tracer.spanBuilder("example-operation").startSpan();

        try {
            // Your business logic here
            System.out.println("Hello from OpenTelemetry!");
        } finally {
            span.end();
        }
    }
}

In this example, we use a Jaeger exporter to send trace data to a Jaeger backend. However, you can easily swap out the exporter for any other supported backend, including Prometheus or the Stackify APM Otel Agent.

Instrumentation

With OpenTelemetry configured, the next step is to instrument your Java application. Instrumentation involves adding code to capture your application’s telemetry data, such as traces and metrics. OpenTelemetry makes this process relatively straightforward by providing APIs and libraries that you can use directly within your code.

The most common types of instrumentation include:

  • Automatic Instrumentation: OpenTelemetry supports automatic instrumentation, where the library automatically captures telemetry data from common Java libraries and frameworks (e.g., HTTP clients, databases). Check out the GitHub library for a great way to get started quickly without modifying your codebase extensively
  • Manual Instrumentation: You explicitly add spans and metrics to your code using the OpenTelemetry APIs. This approach gives you fine-grained control over what data is collected

For example, to manually instrument a section of your code, you can use the following approach:

Span span = tracer.spanBuilder("database-query").startSpan();

try {
    // Simulate a database query
    Thread.sleep(100);
} catch (InterruptedException e) {
    span.setStatus(StatusCode.ERROR, "Database query interrupted");
} finally {
    span.end();
}

This code snippet creates a new span for a database query, simulates the query with a sleep operation, and ends the span. If an error occurs, the span’s status is updated accordingly.

Exporting Metrics, Logs, and Trace Data

Once your application is instrumented, you’ll want to export the collected telemetry data to a backend for analysis. OpenTelemetry supports various exporters, allowing you to send your data to popular observability platforms like Jaeger, Prometheus, or Stackify APM.

For example, you can configure Jaeger to export traces to a Jaeger backend, as shown in the earlier configuration example. Similarly, you would use the OpenTelemetry Prometheus exporter to export metrics to Prometheus.

Exporting telemetry data to a backend enables you to visualize and analyze the data in real time. This helps you gain insights into your application’s performance, identify issues before they impact users, and make data-driven decisions to improve your software.

A Word on Stackify APM

Stackify APM is a reliable application performance management solution that integrates seamlessly with OpenTelemetry. By exporting Java telemetry data to Stackify APM, you can take advantage of application tracing, error tracking, and performance management..

Stackify APM provides a comprehensive view of your application’s health, allowing you to drill down into individual traces, view comprehensive performance analytics, identify performance bottlenecks, and optimize your code. If you want to enhance your observability practices, consider signing up for a free trial of Stackify APM and see how it can help you monitor, troubleshoot, and optimize your Java applications.

Conclusion

Integrating OpenTelemetry with Java is a powerful way to enhance your applications’ observability. By following the steps outlined in this guide—setting up OpenTelemetry, configuring it, instrumenting your code, and exporting telemetry data—you can gain deep insights into your application’s behavior and performance.

OpenTelemetry provides the tools you need to monitor and optimize your software, whether running a simple monolithic application or a complex microservices architecture. With the ability to export data to various backends, including Stackify APM, you can tailor your observability strategy to fit your unique needs.

For more information on getting started with OpenTelemetry and Java, be sure to check out the OpenTelemetry Java documentation and explore how you can improve your observability practices.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]