Java (OpenTelemetry)
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.jarYour application needs no OpenTelemetry dependency for request spans, logs or exceptions. Add these two only for your own spans and metrics:
<?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=deltaOTEL_EXPORTER_OTLP_ENDPOINTtakes the base URL. The agent appends/v1/traces,/v1/metricsand/v1/logsitself.OTEL_SERVICE_NAMEbecomes the Server Name on every endpoint, task and issue. Version travels inOTEL_RESOURCE_ATTRIBUTES. There is noOTEL_SERVICE_VERSIONvariable.http/protobufis the default since agent 2.0, so the protocol line only states it. Do not set it togrpc: Traceway has no gRPC listener, and the agent then refuses to start withOTLP endpoint must not have a path: /api/otelwhile 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.jarAn 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.0Where 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.jarExample Service
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);
}
}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;
}
}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.jarWhat Arrives With No Application Code
| Traceway | Where it comes from |
|---|---|
| Endpoints, grouped by route pattern | The Spring Web MVC instrumentation sets http.route: @GetMapping("/users/{id}") becomes GET /users/{id} |
| Status codes, including 500 on an unhandled exception | The Servlet instrumentation |
| Issues with the JVM stack trace | Unhandled controller exceptions, recorded with the root cause, not Spring's wrapper exception |
| Logs, linked to the trace that produced them | SLF4J, Logback, Log4j and java.util.logging are bridged with no appender and no configuration |
| Child Spans for database and outgoing HTTP calls | JDBC, 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:
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.yamlWith 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-jobSet the dashboard time picker to the last 15 minutes and check:
- Endpoints. One row
GET /users/{id}with a count of 3, andGET /boomwith status 500. - Issues.
java.lang.IllegalStateException: boom: the handler failedwith the JVM stack trace. - Logs. Three
looking up userlines, each linked to its trace. - Tasks.
cleanup-expired-sessions. - Metrics.
app.sessions_cleanedand thejvm.*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.