OpenTelemetry
Java
Quick Start

Java (OpenTelemetry)

Let a coding agent do this setup
1Install the Traceway skills
2Run it in Claude Code

It adds OpenTelemetry to your Java service and checks that data arrives. How the setup skill works

Instrument a Java service with the OpenTelemetry Java agent and export traces, logs and metrics to Traceway over OTLP/HTTP.

The agent is one JAR that you attach when the JVM starts. It instruments Spring, Servlet containers, JDBC, HTTP clients and logging frameworks at runtime, so there is no OpenTelemetry setup code in your application. The example is a Spring Boot service. Any framework the agent supports works the same way.

Requirements

  • Java 8 or newer for the agent. The example uses Java 21 and Spring Boot 4.
  • A Traceway project created with framework OpenTelemetry, and that project's token.

Install

Download the agent. Use a 2.x release:

curl -L -o opentelemetry-javaagent.jar \
  https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar

Your application needs no OpenTelemetry dependency for request spans, logs or exceptions. Add these two only for your own spans and metrics:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.2.0</version>
    <relativePath/>
  </parent>
 
  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0.0</version>
 
  <properties>
    <java.version>21</java.version>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
 
    <dependency>
      <groupId>io.opentelemetry.instrumentation</groupId>
      <artifactId>opentelemetry-instrumentation-annotations</artifactId>
      <version>2.34.0</version>
    </dependency>
 
    <dependency>
      <groupId>io.opentelemetry</groupId>
      <artifactId>opentelemetry-api</artifactId>
      <version>1.68.0</version>
    </dependency>
  </dependencies>
 
  <build>
    <finalName>app</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

opentelemetry-instrumentation-annotations gives you @WithSpan, and opentelemetry-api gives you meters and counters. The agent supplies the implementation of both, so keep the annotations version in step with the agent's. This guide was checked with agent 2.34.0.

Configure

The agent reads all of this from the process environment.

export OTEL_SERVICE_NAME=my-java-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta
  • OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. The agent appends /v1/traces, /v1/metrics and /v1/logs itself.
  • OTEL_SERVICE_NAME becomes the Server Name on every endpoint, task and issue. Version travels in OTEL_RESOURCE_ATTRIBUTES. There is no OTEL_SERVICE_VERSION variable.
  • http/protobuf is the default since agent 2.0, so the protocol line only states it. Do not set it to grpc: Traceway has no gRPC listener, and the agent then refuses to start with OTLP endpoint must not have a path: /api/otel while your application keeps running without telemetry.
  • The temporality line makes counters and histograms send what changed since the last export, not the running total.

Keep the token out of the command line. The agent sends every JVM argument to Traceway as the resource attribute process.command_args. A token passed as -Dotel.exporter.otlp.headers=... travels with every batch and is readable in the dashboard. Use the environment variable.

Run

Attach the agent with -javaagent, before -jar:

java -javaagent:./opentelemetry-javaagent.jar -jar target/app.jar

An agent flag placed after -jar is passed to your application as a program argument and ignored without a message. The agent is attached when the JVM prints this line at startup:

[otel.javaagent 2026-01-15 10:30:00:855 +0000] [main] INFO io.opentelemetry.javaagent.tooling.VersionLogger - opentelemetry-javaagent - version: 2.34.0

Where you cannot change the command, set the flag through the environment instead:

export JAVA_TOOL_OPTIONS="-javaagent:/path/to/opentelemetry-javaagent.jar"
java -jar target/app.jar

Example Service

src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class DemoApplication {
 
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}
src/main/java/com/example/demo/DemoController.java
package com.example.demo;
 
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.instrumentation.annotations.WithSpan;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class DemoController {
 
  private static final Logger log = LoggerFactory.getLogger(DemoController.class);
 
  private static final LongCounter sessionsCleaned =
      GlobalOpenTelemetry.getMeter("com.example.demo")
          .counterBuilder("app.sessions_cleaned")
          .setDescription("Expired sessions removed by the cleanup job")
          .build();
 
  @GetMapping("/users/{id}")
  public Map<String, Object> user(@PathVariable String id) {
    log.info("looking up user {}", id);
    return loadUser(id);
  }
 
  @WithSpan("load-user")
  Map<String, Object> loadUser(String id) {
    return Map.of("id", id, "name", "User " + id);
  }
 
  @GetMapping("/boom")
  public String boom() {
    throw new IllegalStateException("boom: the handler failed");
  }
 
  @GetMapping("/run-job")
  public Map<String, Object> runJob() {
    return Map.of("cleaned", cleanupExpiredSessions());
  }
 
  @WithSpan(value = "cleanup-expired-sessions", kind = SpanKind.CONSUMER, inheritContext = false)
  int cleanupExpiredSessions() {
    int cleaned = 7;
    sessionsCleaned.add(
        cleaned, Attributes.of(AttributeKey.stringKey("job"), "cleanup-expired-sessions"));
    return cleaned;
  }
}
src/main/resources/application.properties
server.port=${PORT:8080}

Build it and start it with the variables from Configure set:

mvn -DskipTests package
java -javaagent:./opentelemetry-javaagent.jar -jar target/app.jar

What Arrives With No Application Code

TracewayWhere it comes from
Endpoints, grouped by route patternThe Spring Web MVC instrumentation sets http.route: @GetMapping("/users/{id}") becomes GET /users/{id}
Status codes, including 500 on an unhandled exceptionThe Servlet instrumentation
Issues with the JVM stack traceUnhandled controller exceptions, recorded with the root cause, not Spring's wrapper exception
Logs, linked to the trace that produced themSLF4J, Logback, Log4j and java.util.logging are bridged with no appender and no configuration
Child Spans for database and outgoing HTTP callsJDBC, Hibernate, HTTP client and Redis instrumentation

Exceptions that reach the servlet container are recorded as span events and show up in Issues. Traceway groups them by the exception class plus the normalized frame list. The message is stripped and Java, Kotlin and Scala line numbers are removed, so one failure keeps a single issue across redeploys and across differing error messages. A different call site, or a frame added or removed in the same path, is a different issue by design.

Two caveats worth knowing. The message is stripped only from the first line of the header, and only when the exception class name contains no $. Exceptions from nested classes, and exceptions whose message spans several lines, can therefore split into one issue per distinct message.

Logs

There is nothing to set up. Every line your application and its libraries log is exported, with the trace id of the request it was written in.

That includes framework output, such as Spring and Tomcat startup lines. Tomcat logs through java.util.logging, so its error for a failed request arrives with severity SEVERE, not ERROR. To send no logs at all, set OTEL_LOGS_EXPORTER=none.

Custom Spans and Background Tasks

@WithSpan puts a span around a method. On a method called inside a request it becomes a child span on that endpoint's waterfall:

@WithSpan("load-user")
Map<String, Object> loadUser(String id) { ... }

A cron job or queue consumer appears under Tasks when its span has kind CONSUMER. A root span with the default kind is dropped.

@WithSpan(value = "cleanup-expired-sessions", kind = SpanKind.CONSUMER, inheritContext = false)
int cleanupExpiredSessions() { ... }

The span name is the task name, so keep it stable. inheritContext = false makes the job the root of its own trace. It matters when the job is started from inside a request, as in this example. Queue listeners the agent knows, such as Kafka, RabbitMQ and JMS, get their CONSUMER span from the agent with no annotation.

Custom Metrics

Ask GlobalOpenTelemetry for a meter. The agent has already configured it:

LongCounter sessionsCleaned =
    GlobalOpenTelemetry.getMeter("com.example.demo")
        .counterBuilder("app.sessions_cleaned")
        .build();
 
sessionsCleaned.add(7, Attributes.of(AttributeKey.stringKey("job"), "cleanup-expired-sessions"));

The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. Metrics export every 60 seconds by default. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.

The agent also sends twelve jvm.* metrics (memory, garbage collection, threads, CPU) and one HTTP histogram, http.server.request.duration, with a series per route, method and status.

Dropping the HTTP histogram

Traceway already computes request counts and latency from spans, so the HTTP histogram repeats them. The agent has no environment variable that removes one metric. A declarative configuration file does it with a view:

otel-config.yaml
file_format: "1.2"
 
resource:
  attributes_list: ${OTEL_RESOURCE_ATTRIBUTES}
  detection/development:
    detectors:
      - service:
 
propagator:
  composite:
    - tracecontext:
    - baggage:
 
tracer_provider:
  processors:
    - batch:
        exporter:
          otlp_http:
            endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces
            headers_list: ${OTEL_EXPORTER_OTLP_HEADERS}
 
meter_provider:
  readers:
    - periodic:
        interval: ${OTEL_METRIC_EXPORT_INTERVAL:-60000}
        exporter:
          otlp_http:
            endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics
            headers_list: ${OTEL_EXPORTER_OTLP_HEADERS}
            temporality_preference: delta
  views:
    - selector:
        instrument_name: http.server.*
      stream:
        aggregation:
          drop:
 
logger_provider:
  processors:
    - batch:
        exporter:
          otlp_http:
            endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/logs
            headers_list: ${OTEL_EXPORTER_OTLP_HEADERS}
export OTEL_CONFIG_FILE=./otel-config.yaml

With OTEL_CONFIG_FILE set, the agent stops reading the OTEL_* variables by itself. Only the ${...} references in the file bring them in, which is why the file names each endpoint with its full path. Declarative configuration is marked experimental in the agent, and agent 2.34.0 expects file_format: "1.2".

Verify It Worked

Start the service, then send a few requests:

curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-job

Set the dashboard time picker to the last 15 minutes and check:

  1. Endpoints. One row GET /users/{id} with a count of 3, and GET /boom with status 500.
  2. Issues. java.lang.IllegalStateException: boom: the handler failed with the JVM stack trace.
  3. Logs. Three looking up user lines, each linked to its trace.
  4. Tasks. cleanup-expired-sessions.
  5. Metrics. app.sessions_cleaned and the jvm.* names in metric discovery.

Nothing at all? Look for the opentelemetry-javaagent - version line in the startup output. If it is missing, the agent is not attached. If the JVM printed OpenTelemetry Javaagent failed to start, the line after it says why.

Next Steps

  • Traces: how OTel spans map to Endpoints, Tasks and Issues
  • Logs: log record mapping and severity handling
  • Metrics: supported metric types and histogram handling
  • Overview: protocol details, authentication, and a "nothing is showing up" checklist