OpenTelemetry Java Configuration

Ship traces from Java to OpenSearch with OpenTelemetry

Use OpenTelemetry to easily send Java traces to your Logit.io Stack.

This sample app was created and tested with

  • java version "22.0.2" 2024-07-16
  • Apache Maven 3.9.8 (36645f6c9b5079805ea5009217e36f2cffd34256)

Install Integration

Please click on the Install Integration button to configure your stack for this source.

Install

Open the command prompt or terminal and navigate to where you want your project to live, then paste in the following command:

mvn archetype:generate -DgroupId=logit.apm.testapp -DartifactId=java-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

You will see that a folder has been created called 'logit-apm-test-app', navigate into this folder and you will see a file called pom.xml.

Open this file using your preferred text editor, then copy and paste the code below into the file and save the changes:

<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>logit.apm.testapp</groupId>
  <artifactId>java-project</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>java-project</name>
  <url>http://maven.apache.org</url>
 
  <properties>
      <!-- https://maven.apache.org/general.html#encoding-warning -->
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
 
  <dependencies>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>io.opentelemetry</groupId>
        <artifactId>opentelemetry-api</artifactId>
        <version>1.30.1</version>
      </dependency>
      <dependency>
          <groupId>io.opentelemetry</groupId>
          <artifactId>opentelemetry-sdk</artifactId>
          <version>1.30.1</version>
      </dependency>
      <dependency>
          <groupId>io.opentelemetry</groupId>
          <artifactId>opentelemetry-exporter-otlp</artifactId>
          <version>1.30.1</version>
      </dependency>
  	    <dependency>
        <groupId>io.opentelemetry</groupId>
        <artifactId>opentelemetry-exporter-jaeger</artifactId>
        <version>1.10.0</version>
      </dependency>
  </dependencies>
    <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
            <!-- Attach the shade goal into the package phase -->
          <execution>
              <phase>package</phase>
              <goals>
                  <goal>shade</goal>
              </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.0</version>
          <executions>
          <!-- Attach the shade into the package phase -->
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <transformers>
                  <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>logit.apm.testapp.App</mainClass>
                  </transformer>
                </transformers>
              </configuration>
            </execution>
          </executions>
      </plugin>
    </plugins>
  </build>
</project>

Configuring the App

In the same folder create a new file called config.properties and then open it with your text editor

Paste the following code into the file and then save the changes.

⚠️

You will need to update any placeholder variables with your OpenTelemetry details.

ENDPOINT=https://@opentelemetry.endpointAddress
PORT="@opentelemetry.httpsPort:strip_quotes"
USERNAME="@opentelemetry.username:strip_quotes"
PASSWORD="@opentelemetry.password:strip_quotes"

Next we need to navigate to the following folder:

src -> main -> java -> logit -> -apm -> testapp

Here you will find a file called App.java, this file will contain our app code.

Open the folder using your text editor and paste the following code:

package logit.apm.testapp;
 
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter;
 
import java.util.Base64;
import java.time.Duration;
 
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
 
public class App {
 
    public static void main(String[] args) {
    
    // Define the service name as a resource attribute
    Resource resource = Resource.create(Attributes.of(AttributeKey.stringKey("service.name"), "LogitJavaTestApp"));
    
    Properties properties = new Properties();
  
    try (FileInputStream input = new FileInputStream("./config.properties")) {
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    String endpoint = properties.getProperty("ENDPOINT");
    String port = properties.getProperty("PORT");
    String username = properties.getProperty("USERNAME");
    String password = properties.getProperty("PASSWORD");
    String encodeBytes = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
    
    // Configure the OTLP exporter with basic auth
        OtlpGrpcSpanExporter spanExporter = OtlpGrpcSpanExporter.builder()
                .setEndpoint(endpoint + ":" + port) // Replace with your OTLP endpoint
                .addHeader("Authorization", "Basic " + encodeBytes)
                .build();
 
        // Set up the SDK tracer provider
        SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
        .setResource(resource) 
                .addSpanProcessor(BatchSpanProcessor.builder(spanExporter)
                        .setScheduleDelay(Duration.ofMillis(100))
                        .build())
                .build();
 
        OpenTelemetrySdk openTelemetrySdk = OpenTelemetrySdk.builder()
                .setTracerProvider(tracerProvider)
                .buildAndRegisterGlobal();
 
        // Get a tracer
        Tracer tracer = GlobalOpenTelemetry.getTracer("com.example.App");
 
        // Create a span
        Span span = tracer.spanBuilder("Logit Span Test").startSpan();
    
    LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
    
        span.setAttribute("First Message", "This is a test!");
    span.setAttribute("Second Message", "Message sent at " + formattedDateTime);
    
        span.addEvent("Test Log Event 1");
        span.addEvent("Test Log Event 2");
 
        span.end();
 
        // Shut down the SDK
        tracerProvider.close();
 
        System.out.println("App ran successfully");
    }
}

We are now ready to run the app.

Run the Python App

Navigate back to the logit-apm-test-app folder, the folder that contains your pom.xml file using either the command prompt or terminal window.

Run the following command to build the project.

mvn package

As the project compiles the process and results are written to the command prompt or terminal window.

Still in the logit-apm-test-app folder, using the command prompt or terminal window, run the following command:

java -jar target/java-project-1.0-SNAPSHOT.jar

You will see that a message is returned to say that the app ran successfully.

The action of running the Java app will send traces to your Stack. You can now view these traces in Jaeger.

Launch Logit.io to view your traces

Launch APM

How to diagnose no data in Stack

If you don't see data appearing in your Stack after following the steps, visit the Help Centre guide for steps to diagnose no data appearing in your Stack or Chat to support now.