boltZharp Docs
settingsSDKs

Rust

The zharp crate traces every request your Axum, Actix Web or tonic service handles, its SQLx queries and reqwest calls, and sends its panics, errors and failed queries with readable stacks.

info
zharp 0.1.0

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

One crate, built on OpenTelemetry Rust (0.33) and the tracing crate that nearly every Rust library already logs and times through. Each framework and library is a Cargo feature, so only what you switch on is compiled. It needs no Tokio runtime of its own: plain binaries, CLIs and workers work too. Anything else you instrument with OpenTelemetry or tracing is sent as well.

Quickest setup

In the crate's folder, run the setup (it needs Node.js only to run). It opens a page to pick the Zharp app, finds your framework in Cargo.toml, runs cargo add zharp with the features you need (sqlx, reqwest and anyhow when you use them), starts Zharp in main.rs and adds the layer or middleware when it finds the router (it prints them otherwise), keeps line numbers in release builds and writes ZHARP_KEY to .env. It shows every change before making it.

npm init zharp@latest

The rest of this page is what it sets up, by hand.

Install

cargo add zharp -F axum            # or -F actix, -F tower; nothing for a plain binary
cargo add zharp -F axum,sqlx,reqwest,anyhow   # with the libraries you use
FeatureWhat it adds
axumzharp::axum::layer() and Reported<E>
actixzharp::actix::Middleware
towerzharp::tower::layer(), for any Tower service: tonic, Poem, Salvo, hyper
sqlxa span per query, and failed queries with their statement — see Failed queries
reqwesta span per outgoing call, with traceparent — see HTTP calls
anyhowanyhow errors keep the stack from where they were created
sdkon by default: the SDK itself (turn default features off only for build.rs)

Initialize

Set your key, from the app's settings in Zharp:

ZHARP_KEY=zpk_… cargo run --release   # Application settings in Zharp

and start Zharp first in main:

fn main() {
    let _zharp = zharp::init!();   // first; keep the guard

    // your program
}

zharp::init!() is a macro, not a function: it reads your package's name and version, and the build ID, when it compiles, so the service and release are named for you. Keep the guard it returns: it sends what's left when main ends. Without a key it sends nothing and says so once. To set options in code:

let _zharp = zharp::init!(
    zharp::Options::new()
        .environment("production")
        .logs(true),
);

Axum

After cargo add zharp -F axum, add the layer to the Router, after its routes:

#[tokio::main]
async fn main() {
    let _zharp = zharp::init!();

    let app = Router::new()
        .route("/orders/{id}", get(show_order))
        .layer(zharp::axum::layer());   // after the routes

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Requests are named by their route (Axum's MatchedPath, GET /orders/{id}) and continue the caller's trace. A handler that panics answers 500 and the panic is reported once.

Errors your handlers return

By the time the layer sees a returned error it is only a 500. Wrap your error type in Reported: ? converts any error into it and takes the stack there, your AppError still makes the response, and it is reported once when it answers 5xx (a 4xx isn't reported).

use zharp::axum::Reported;

async fn show_order(Path(id): Path<i64>) -> Result<Json<Order>, Reported<AppError>> {
    let order = find_order(id).await?;   // ? converts the error and takes the stack here
    Ok(Json(order))
}

Actix Web

After cargo add zharp -F actix, wrap the App:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let _zharp = zharp::init!();

    HttpServer::new(|| {
        App::new()
            .wrap(zharp::actix::Middleware)
            .service(show_order)
    })
    .bind(("0.0.0.0", 8080))?
    .run()
    .await
}

Requests are named by their route pattern. A 5xx error a handler returns is reported once, and a panic answers 500 and is reported.

tonic, Poem, Salvo and other Tower services

The tower feature's layer works on any Tower service:

// cargo add zharp -F tower
Server::builder()
    .layer(zharp::tower::layer())
    .add_service(GreeterServer::new(greeter))
    .serve(addr)
    .await?;

Plain binaries: CLIs and workers

cargo add zharp and zharp::init!() first in main, as above. A panic is reported with its backtrace and waits up to two seconds to be sent before the process goes on as it would have. Wrap a job in a span (Tracing) to see its logs, queries and errors as one trace.

Logs

Off by default. zharp::init!() sets up a tracing subscriber, unless your app already set one: it prints each line with trace_id=… span_id=… appended, filtered by RUST_LOG (info by default), and lines from the log crate come through it too. 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.

Where there is no agent, send the lines from the SDK instead:

ZHARP_LOGS=true

zharp::log is always sent.

Your own subscriber

If you build the subscriber yourself, add Zharp's two layers to it and tell init! not to install one (the order of the two doesn't matter):

use tracing_subscriber::prelude::*;

tracing_subscriber::registry()
    .with(zharp::fmt_layer())   // in place of tracing_subscriber::fmt::layer(): stamps each line
    .with(zharp::layer())       // spans, errors and (with ZHARP_LOGS=true) logs to Zharp
    .init();

let _zharp = zharp::init!(zharp::Options::new().install_subscriber(false));

With a custom fmt layer, stamp its writer instead:

tracing_subscriber::fmt::layer().with_writer(zharp::stamp(std::io::stderr))

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.

// ZHARP_KEY, ZHARP_SERVICE, ZHARP_TRACING=false and ZHARP_LOGS=true in the environment
fn main() {
    let _zharp = zharp::init!();
}

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 type (sqlx::error::Error), its message with the source() chain, and its stack — not again for a later 500, nor for the same error logged higher up. They come from:

  • Panics, with a backtrace taken where they happened. No RUST_BACKTRACE needed.
  • A tracing::error! with an error (or err) field — %e, ?e or &e as &dyn Error — with the stack where it was logged. Most Rust apps already log their errors this way.
  • Axum handlers returning Reported<E> and Actix Web handlers returning a 5xx error.
  • With the anyhow feature, an anyhow::Error keeps the stack from where it was created (the feature sets RUST_LIB_BACKTRACE=1 when it isn't set).

Report one yourself:

// a tracing::error! with an error (or err) field is the request's error, with the stack where it was logged
tracing::error!(error = %e, "payment failed");

// an error you handled
zharp::capture_error(&e);
zharp::capture_anyhow(&e);                  // keeps the stack from where the anyhow::Error was created
zharp::capture_message("cache rebuilt from scratch");

Readable stack traces

Since Rust 1.77 a release build strips debug info, so a stack names functions but not files or lines. Keep the line tables in the binary: the process then reads its own files and lines, and there is nothing to upload.

# Cargo.toml
[profile.release]
debug = "line-tables-only"

The binary grows, often by 10–30%; speed doesn't change. npm init zharp adds it. Don't strip the binary afterwards (strip = true, or strip in a Dockerfile): that removes the lines again. In Docker, Cargo reads the same setting from the environment:

# Dockerfile: the same, without touching Cargo.toml
FROM rust:1 AS build
WORKDIR /app
COPY . .
ENV CARGO_PROFILE_RELEASE_DEBUG=line-tables-only
RUN cargo build --release

FROM debian:bookworm-slim
COPY --from=build /app/target/release/my-app /usr/local/bin/my-app
CMD ["my-app"]

The code that ran

Errors also show the source around each of your frames. Link a repository in Zharp and there is nothing to do. Otherwise, upload a source bundle: a build.rs writes a build ID into the binary, which the SDK sends with every error, and the CLI uploads src/ under the same ID. The ID is a hash of src/**/*.rs, so both sides agree without passing it.

// build.rs, next to Cargo.toml
fn main() {
    zharp::build::id();
}
# Cargo.toml
[build-dependencies]
zharp = { version = "0.1", default-features = false }
# in CI, from the crate's folder, after the build
npx @zharp/cli sources upload --app <app id>

The upload needs a workspace API key with the artifacts:write scope in ZHARP_AUTH_TOKEN — see The upload key. The app ID is on the app's setup page; ZHARP_URL points at another Zharp. More: Zharp CLI.

Tracing

Each request is named by its route and continues the caller's traceparent, with spans for queries and HTTP calls under it. Spans you make with tracing are sent too:

#[tracing::instrument(skip(db))]
async fn charge(db: &PgPool, order_id: i64) -> Result<(), Error> {
    // a span named charge, with order_id on it
}

Request and response headers

Every request and response header is recorded on the request's span. Secret ones — authorization, cookies, API keys, tokens, sessions — are recorded as [REDACTED], and secret-looking query values in URLs are masked. ZHARP_CAPTURE_HEADERS=false turns headers off.

Failed queries

With the sqlx feature, each query becomes a span, from SQLx's own query events. A failed query's error carries the database, the Postgres or MySQL error code, the constraint and the statement (with $1 placeholders, not values). Where Zharp can't tell the database, set ZHARP_DB_SYSTEM. ZHARP_CAPTURE_QUERY_ERRORS=false turns it off.

HTTP calls

With the reqwest feature, each outgoing call is a span and carries traceparent, so the trace continues in the service it calls:

let client = zharp::reqwest::wrap(reqwest::Client::new());

// or, on a reqwest_middleware client
let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
    .with(zharp::reqwest::Middleware)
    .build();

User context

Requests from the Zharp browser and mobile SDKs carry the user and session in baggage, and every span, log and error of the request gets them with no code. When the server knows the user better:

zharp::set_user(zharp::User::id("u_42").with_email("ada@example.com"));

The API

zharp::capture_error(&e);                        // an error you handled
zharp::capture_anyhow(&e);                       // the same, with anyhow's own stack
zharp::capture_message("cache rebuilt");         // a message, as an error event
zharp::set_user(zharp::User::id("u_42").with_email("ada@example.com"));
zharp::clear_user();
zharp::set_tag("tenant", "acme");                // on every span and log from now on
zharp::log(zharp::Level::Info, "order paid", &[("order_id", "42")]);   // sent whatever ZHARP_LOGS says
zharp::flush(Duration::from_secs(2));            // send what's queued now

Options

Every setting comes from the environment; zharp::Options sets some in code.

EnvironmentDefault
ZHARP_KEY—The application's ingest key. Without it nothing is sent.
ZHARP_SERVICEthe package nameservice.name
ZHARP_ENVIRONMENT—deployment.environment.name
ZHARP_RELEASEthe package version, plus the git SHA when build.rs ranservice.version
ZHARP_ENDPOINThttps://api.zharp.io/api/v1/otlpOTLP over HTTP (protobuf).
ZHARP_SAMPLE_RATE1.0Share of traces kept.
ZHARP_TRACINGtruefalse: errors and logs only.
ZHARP_LOGSfalseSend log lines straight to Zharp. See Logs.
ZHARP_LOG_CORRELATIONtrueThe trace_id=… span_id=… stamp.
ZHARP_CAPTURE_HEADERStrueRequest and response headers. See headers.
ZHARP_CAPTURE_QUERY_ERRORStrueFailed queries reported with their statement.
ZHARP_DB_SYSTEM—The database, where SQLx doesn't say.
ZHARP_BUILD_IDfrom build.rsThe source bundle's ID. See The code that ran.
ZHARP_DISABLEDfalsetrue turns everything off.
  • zharp::flush(Duration) sends what's queued now; the guard from init! does it when it drops.

Supported versions

  • Rust 1.85 and later, on Linux, macOS and Windows.
  • Axum 0.8, Actix Web 4, tonic 0.14 and any Tower service; SQLx 0.9; reqwest 0.13.
  • Built on OpenTelemetry Rust 0.33.

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 the guard kept? let _ = zharp::init!(); drops it at once and stops Zharp; it needs a name, such as _zharp.
  • Axum: is the layer added after the routes? A layer only wraps the routes added before it.
  • Your own subscriber set before init!? Add zharp::layer() to it — see Your own subscriber — or Zharp gets no spans or errors from tracing.
  • Stacks with function names but no files or lines: the release build has no line tables — see Readable stack traces.

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.