boltZharp Docs
coffeeSDKs

Java

The Zharp Java agent traces every request your Spring Boot, Spring, Kotlin or other JVM server handles, and sends its errors and failed queries — no code changes.

info
io.zharp:zharp-agent 0.1.0

This SDK is new, and its API may still change before 1.0. Requires Java 8 or later.

Spring Boot, Spring, plain servlets, Ktor, Quarkus, Micronaut, Javalin — anything on the JVM. The agent is OpenTelemetry's Java agent (instrumentation 2.34.0, SDK 1.68.0) with Zharp's settings and additions, as one jar. Alongside it:

ArtifactWhat it is
io.zharp:zharp-agentThe agent (recommended). No code changes.
io.zharp:zharp-apiThe API — captureError, setUser, setTag, log, startSpan, flush — for apps run with the agent or the starter.
io.zharp:zharpThe API plus the OpenTelemetry SDK: library mode, for apps that run without the agent.
io.zharp:zharp-spring-boot-starterSpring Boot without an agent: GraalVM native images, hosts that forbid agents.
io.zharp.java (Gradle), io.zharp:zharp-maven-pluginBuild plugins: errors show the code of the build that ran.

Install

Download the agent once (or take io.zharp:zharp-agent:0.1.0 from Maven Central):

curl -fLo zharp-agent.jar https://github.com/zharp-io/zharp-java-lib/releases/latest/download/zharp-agent.jar

Initialize

Start the app with the agent and your app's key, from the app's settings in Zharp:

export ZHARP_KEY=zpk_…            # Application settings in Zharp
export ZHARP_SERVICE=orders-api   # optional: defaults to the jar's name
export ZHARP_ENVIRONMENT=production
java -javaagent:zharp-agent.jar -jar app.jar

The first line it prints says it's on:

[Zharp] Application monitoring active — service "orders-api", environment "production"

Without a key it sends nothing. The app's setup page in Zharp shows these steps with the key, service and environment filled in.

Docker

FROM eclipse-temurin:21-jre
ADD https://github.com/zharp-io/zharp-java-lib/releases/latest/download/zharp-agent.jar /opt/zharp-agent.jar
COPY build/libs/app.jar /app.jar
ENV JAVA_TOOL_OPTIONS="-javaagent:/opt/zharp-agent.jar"
ENTRYPOINT ["java", "-jar", "/app.jar"]

Pass ZHARP_KEY at run time (docker run -e ZHARP_KEY=zpk_… …), not in the image.

When you can't change the command

Every JVM started with JAVA_TOOL_OPTIONS picks the agent up — Tomcat, Jetty, WildFly, a platform's start script:

export JAVA_TOOL_OPTIONS="-javaagent:/opt/zharp-agent.jar"

# a standalone Tomcat: in bin/setenv.sh
CATALINA_OPTS="-javaagent:/opt/zharp-agent.jar"

Gradle bootRun and run

// build.gradle.kts
val zharpAgent = configurations.create("zharpAgent")
dependencies { zharpAgent("io.zharp:zharp-agent:0.1.0") }

tasks.named<JavaExec>("bootRun") {   // "run" for the application plugin (Kotlin, Ktor…)
    jvmArgumentProviders.add(CommandLineArgumentProvider { listOf("-javaagent:${zharpAgent.singleFile}") })
}

Maven spring-boot:run

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution>
      <id>zharp-agent</id>
      <phase>initialize</phase>
      <goals><goal>copy</goal></goals>
      <configuration>
        <artifactItems>
          <artifactItem>
            <groupId>io.zharp</groupId>
            <artifactId>zharp-agent</artifactId>
            <version>0.1.0</version>
            <destFileName>zharp-agent.jar</destFileName>
          </artifactItem>
        </artifactItems>
        <outputDirectory>${project.build.directory}</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <agents><agent>${project.build.directory}/zharp-agent.jar</agent></agents>
  </configuration>
</plugin>

Spring Boot without the agent: the starter

For GraalVM native images and hosts that forbid agents. It is OpenTelemetry's Spring Boot starter (Spring MVC and WebFlux, RestTemplate/WebClient, JDBC, Logback, Kafka, MongoDB, R2DBC) configured for Zharp, with everything on this page: errors once, failed queries, headers, users, the log-line stamp. Spring Boot 2.7 and 3.x. The agent covers more libraries.

// build.gradle.kts
dependencyManagement {
    // OpenTelemetry's versions, not the older ones Spring Boot manages.
    imports { mavenBom("io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom:2.34.0") }
}
dependencies {
    implementation("io.zharp:zharp-spring-boot-starter:0.1.0")
}
# application.properties — or ZHARP_KEY, ZHARP_SERVICE… in the environment
zharp.key=${ZHARP_KEY}
zharp.environment=production
# zharp.service defaults to spring.application.name
# zharp.logs=true

Library mode: no agent

For tests, CLIs and jobs, or wherever agents aren't allowed — first thing in main, with io.zharp:zharp (the API plus the OpenTelemetry SDK it starts):

Zharp.init();   // reads ZHARP_KEY, ZHARP_SERVICE… — or:
Zharp.init(ZharpOptions.builder().key("zpk_…").service("nightly-export").environment("production").build());

Only what you wrap with Zharp.startSpan is traced; errors (captureError, uncaught exceptions on any thread) and Zharp.log are sent, and Logback lines are stamped. With io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0 (or the Log4j 2 one) on the classpath, ZHARP_LOGS=true sends their records too. A job started by another service continues its trace from TRACEPARENT / BAGGAGE with OpenTelemetry's propagator (Zharp.openTelemetry().getPropagators()).

The API

implementation("io.zharp:zharp-api:0.1.0")    // Gradle

<dependency><groupId>io.zharp</groupId><artifactId>zharp-api</artifactId><version>0.1.0</version></dependency>
import io.zharp.Zharp;
import io.zharp.ZharpUser;

Zharp.setUser(ZharpUser.of(user.getId()).withEmail(user.getEmail()));  // this request's user
Zharp.setTag("region", "eu-west-1");                                   // on everything from now on

try {
    charge(order);
} catch (PaymentException e) {
    Zharp.captureError(e);                                             // handled, in this request's trace
}

Zharp.log.info("Order placed", Map.of("orderId", order.getId()));      // always sent
Zharp.startSpan("rebuild-index", span -> index.rebuild());
Zharp.flush();                                                         // before a short-lived process exits

io.zharp:zharp-api is the API alone, for apps run with the agent or the starter: these calls go through them. In library mode use io.zharp:zharp instead, which includes it. Same package and classes either way. Nothing here throws into your app.

Logs

Off by default. With the agent, every line Logback or Log4j 2 writes during a request through a pattern layout (Spring Boot's console format, %d %-5level %logger - %msg%n…) ends with the request's trace_id=… span_id=…; JSON encoders get trace_id and span_id fields from the MDC. Where the Zharp agent reads your app's output, it brings those lines in and links each one to its request — one copy, nothing sent twice. ZHARP_LOG_CORRELATION=false turns the stamp off.

To send Logback and Log4j 2 records straight to Zharp instead, with their level, logger, thread and exception:

export ZHARP_LOGS=true

Zharp.log is always sent.

Logs only

If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests. A request from a Zharp front end is still read, so its logs keep the caller's user, session and trace ID.

export ZHARP_KEY=zpk_…
export ZHARP_SERVICE=checkout-api
export ZHARP_TRACING=false
export ZHARP_LOGS=true   # Logback and Log4j 2 records, not only Zharp.log
java -javaagent:zharp-agent.jar -jar app.jar

The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.

Errors

A request that fails is reported once, with its stack — not again for every span the exception crossed, nor for the container's log line about it. Uncaught exceptions on any thread are reported, and exceptions you log at ERROR are reported as handled. Report one yourself:

try {
    charge(order);
} catch (PaymentException e) {
    Zharp.captureError(e);   // reported as handled, in this request's trace
}

Readable stack traces

Nothing to upload for the stack: Java and Kotlin frames already name your classes, methods, files and lines, and issues are grouped by them.

The code that ran: build plugins

Errors also show the source around each of your frames. Link a repository in Zharp, or upload each build's sources with a build plugin. The plugin writes a build ID into the jar (META-INF/zharp/build.properties) and uploads your .java/.kt files under it; the agent, the starter and library mode send that ID with every error, so the code shown is that build's. In a multi-module build every module's sources go up under one ID: apply the Gradle plugin to the app or the root project, or declare the Maven plugin in the parent POM, so every jar carries the ID.

// build.gradle.kts
plugins { id("io.zharp.java") version "0.1.0" }
zharp { appId = "123" }   // the application's ID in Zharp
<plugin>
  <groupId>io.zharp</groupId>
  <artifactId>zharp-maven-plugin</artifactId>
  <version>0.1.0</version>
  <configuration><appId>123</appId></configuration>
  <executions>
    <execution><goals><goal>build-id</goal><goal>upload-sources</goal></goals></execution>
  </executions>
</plugin>

The upload needs a workspace API key with the artifacts:write scope in ZHARP_AUTH_TOKEN (CI secrets, or zharp.authToken in ~/.gradle/gradle.properties) — see The upload key. Without one the build still gets its ID and says what it would upload. The app ID can also come from ZHARP_APP_ID; ZHARP_URL points at another Zharp. Gradle runs the upload after assemble, Maven at package. includeSources = false / <includeSources>false</includeSources> writes the ID only.

Tracing

Every library OpenTelemetry's agent knows is traced: Spring MVC and WebFlux, Servlet, JAX-RS, Ktor, JDBC, Hibernate, R2DBC, Kafka, RabbitMQ, gRPC, HTTP clients, Redis, Mongo… Each request continues the caller's trace. Add your own spans with Zharp.startSpan.

Request and response headers

Every request and response header is recorded, so a failed request shows what was sent and what came back. Secret ones —authorization, cookie, API keys, tokens — are recorded as [Filtered]: you see one was sent, never its value. ZHARP_CAPTURE_HEADERS_REDACT adds more names; ZHARP_CAPTURE_HEADERS=false turns them off.

Database queries

A query that fails is reported with its statement, the database and the SQLSTATE — Postgres errors named by their code (UniqueViolation). Row values are never sent. ZHARP_CAPTURE_QUERY_ERRORS=false turns it off.

User context

Requests from the Zharp browser and mobile SDKs carry the user and session in baggage; the agent puts them on every span and log of the request. When the server knows better, with io.zharp:zharp:

Zharp.setUser(ZharpUser.of(user.getId()).withEmail(user.getEmail()));   // this request's user, when the server knows better

Options

Environment variables, or -D system properties with the lower-case dotted names: -Dzharp.key=…, -Dzharp.logs=true.

Environment (or -D property)Default
ZHARP_KEY (ZHARP_API_KEY)—The application's ingest key. Without it nothing is sent.
ZHARP_SERVICEthe jar or main class nameservice.name
ZHARP_ENVIRONMENT (ZHARP_ENV)—deployment.environment.name
ZHARP_RELEASE (ZHARP_VERSION)—service.version
ZHARP_ENDPOINThttps://api.zharp.io/api/v1/otlp
ZHARP_LOGSfalseSend Logback / Log4j 2 records. See Logs.
ZHARP_TRACINGtruefalse: logs only — requests still get trace ids, no spans are sent.
ZHARP_LOG_CORRELATIONtrueThe trace_id=… span_id=… stamp.
ZHARP_CAPTURE_HEADERStrueRequest and response headers. See headers.
ZHARP_CAPTURE_HEADERS_REDACT—More header names to filter, comma-separated.
ZHARP_CAPTURE_QUERY_ERRORStrueFailed queries reported with their statement.
ZHARP_CAPTURE_UNCAUGHTtrueUncaught exceptions on any thread.
ZHARP_SAMPLE_RATE1Share of traces kept.
ZHARP_DISABLED—true: send nothing.
ZHARP_DEBUG—Print what goes wrong inside Zharp.
  • With the agent, OpenTelemetry's own OTEL_* / -Dotel.* settings still work for everything Zharp doesn't set — turning an instrumentation off, for one: -Dotel.instrumentation.jdbc.enabled=false.
  • Zharp.flush() sends now — before a short-lived process exits.

Troubleshooting

Nothing arrives

On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:

  • Is init called, and before the code you expect to see? Without a key, the SDK starts nothing and says so once.
  • Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key, service decides the app — see Keys.
  • Data is sent in batches every few seconds. A process that exits straight away should call flush first.
  • Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
  • Is -javaagent: on the command that actually starts the JVM? The first line it prints says it's on.
  • Running from Gradle or Maven? bootRun, run and spring-boot:run need the agent added to the task — see Gradle and Maven.

401 or 403

Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.