boltZharp Docs
diamondSDKs

Ruby

The zharp gem traces every request your Rails, Sinatra or Rack app handles, its jobs, queries and HTTP calls, and sends its errors and failed queries — in Rails, with no code.

info
zharp 0.1.0

This SDK is new, and its API may still change before 1.0. Requires Ruby 3.3 or later (3.3, 3.4, 4.0) and, for Rails, Rails 7.1 or later.

One gem for Rails, any Rack app (Sinatra, Hanami, Roda, Grape), Sidekiq and plain Ruby, built on the official OpenTelemetry SDK. Each integration switches itself on when its library is loaded: database queries (pg, mysql2, trilogy, Active Record), outgoing HTTP (Net::HTTP, Faraday, HTTP.rb, HTTPX), Redis, jobs (Sidekiq, Active Job, Resque, Delayed Job), Action View and Action Mailer. Anything else you instrument with OpenTelemetry is sent too.

Install

bundle add zharp

Rails

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

ZHARP_KEY=zpk_… bin/rails server   # Application settings in Zharp

or keep it in the credentials:

# bin/rails credentials:edit
zharp:
  key: zpk_…

That's all: the gem's Railtie starts Zharp when Rails boots — in the web server, bin/rails runner, Sidekiq and Solid Queue alike. Without a key it sends nothing. The app's setup page in Zharp shows these steps with the key, service and environment filled in.

The generator

To change a default, generate the initializer. It lists every option commented out; with --key it also stores the key in the credentials:

bin/rails generate zharp:install --key=zpk_…
# config/initializers/zharp.rb: Rails starts Zharp without it; this only changes defaults
Zharp.init(
  # service: "checkout-api",         # ZHARP_SERVICE
  # environment: Rails.env,          # ZHARP_ENVIRONMENT
  # release: ENV["GIT_SHA"],         # ZHARP_RELEASE
  # capture_bodies: "errors",        # ZHARP_CAPTURE_BODIES
  # …every option, commented out
)

Rack apps: Sinatra, Hanami, Roda, Grape

After bundle add zharp, in config.ru, with ZHARP_KEY in the environment:

# config.ru
require "zharp"
Zharp.init(service: "shop")   # optional: options in code; ZHARP_KEY comes from the environment
use Zharp::Rack

run App

Sinatra and Grape requests are named by their routes; others by the path with ids replaced (GET /orders/:id). Call Zharp.init before use to set options in code.

Plain Ruby: scripts, workers, CLIs

require "zharp"
Zharp.init(service: "billing-worker")   # after your gems are required

Call it after your gems are required, so their instrumentation is switched on. An exception that ends the script is reported and sent before it exits.

Jobs: Sidekiq, Active Job, Solid Queue

Jobs run in the trace of the request that queued them, as its children: Sidekiq, and Active Job on any backend (Solid Queue, GoodJob, Delayed Job…). Each job is a span with its errors. In a Rails app this needs nothing.

Sidekiq outside Rails

At the top of the file Sidekiq loads, with ZHARP_KEY in the environment:

# worker.rb: the file Sidekiq loads, first line
require "zharp/sidekiq"

# ZHARP_KEY=zpk_… bundle exec sidekiq -r ./worker.rb

Sidekiq keeps only one -r, so this goes in that file rather than on the command line.

Puma and Unicorn

Forking servers need nothing: Puma in cluster mode (with or without preload_app!) and Unicorn. Each worker starts its own export threads after the fork and sends over a connection of its own.

# config/puma.rb
workers 4
preload_app!   # nothing else to add for Zharp

Logs

Off by default. Each line written through Ruby's Logger — so Rails.logger and lograge — or semantic_logger during a request ends with the request's trace_id=… span_id=… (two fields on a JSON line). 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.

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.

require "zharp"

Zharp.init(key: "zpk_…", service: "checkout-api", tracing: false, logs: true)

Or leave the code as it is and set ZHARP_TRACING=false ZHARP_LOGS=true in the environment.

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 or job that fails is reported once, with its type, message and stack — not again for every span it crossed, nor for the log line about it. Each error carries the code that ran: the lines around your app's innermost five frames, read on your server (never gems or Ruby's own library). Report one yourself:

begin
  charge(order)
rescue PaymentError => e
  Zharp.capture_error(e, order_id: order.id)   # reported as handled, in this request's trace
end

Rails.error.handle { charge(order) }           # Rails' error reporter reaches Zharp too

Readable stack traces

Nothing to upload: the stacks this SDK sends already name your functions, files and lines, and issues are grouped by them.

Tracing

Each request is named by its route and continues the caller's traceparent, with spans for queries, HTTP calls, Redis, views, mailers and jobs under it. Add your own with Zharp.start_span.

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]. Name more to hide, or turn it off:

Zharp.init(capture_headers: { redact: ["x-tenant"] })   # filter more names
Zharp.init(capture_headers: false)                     # or ZHARP_CAPTURE_HEADERS=false

Failed queries

A query that fails is reported once, with the statement (values obfuscated), the database and the error code. Postgres's DETAIL: line, which holds the row's values, is dropped. ZHARP_CAPTURE_QUERY_ERRORS=false turns it off.

Request and response bodies

Off by default. Turn it on to see what a request sent and what came back, shown under the request in the trace: incoming requests in any Rack app (Rails included) and outgoing Net::HTTP calls (Faraday's default adapter too).

# failed requests only; "all" for every one
Zharp.init(capture_bodies: "errors")

# or ZHARP_CAPTURE_BODIES=errors in the environment, or, with more control:
Zharp.init(capture_bodies: {
  mode: "errors",
  max_size: 32_768,
  redact_keys: ["date_of_birth"],
  urls: ["api.example.com"],
})
  • Failed requests only (status 400 and above, or no response) by default; every request with the "all" mode.
  • Text (JSON, forms, XML, plain text) is kept up to 32 KB, up to 128 KB with the size option.
  • Every field name is kept. A file in an upload shows as [file photo.png · image/png · 240 KB], an inline image as [image/png · 24 KB], a body that isn't text as [binary · application/pdf · 1.2 MB] or [event stream]. File contents are never sent.
  • Your app reads and sends exactly what it did before.
  • urls limits it to some requests: a host, a URL prefix or a Regexp.
  • Secret-looking query values in URLs are masked on every span either way.
warning
Bodies can hold personal data

Values under keys that look secret — password, token, secret, apiKey, authorization, cookie, card, cvv, ssn and similar — are replaced with [Filtered] in your process, before anything is sent. The field stays; only its value is hidden, and under a secret object such as card each value inside is hidden and its keys kept. Anything else, such as names and email addresses, is sent as it is: add those keys to redact_keys.

Whether or not bodies are on, secret-looking values in URL query strings (?token=, key, sig, password …) are recorded as [Filtered].

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:

class ApplicationController < ActionController::Base
  before_action { Zharp.set_user(id: current_user.id, email: current_user.email) if current_user }
end

The API

Zharp.capture_error(error, order_id: 42)      # an exception you rescued, as a handled error
Zharp.set_user(id: user.id, email: user.email) # on the request's spans, logs and errors
Zharp.set_tag("tenant", "acme")                # on every span and log from now on
Zharp.log.info("order paid", order_id: 42)     # a log line sent from the SDK, whatever ZHARP_LOGS says
Zharp.start_span("render invoice") { render }  # a span around some work
Zharp.flush                                    # send what's queued now (end of a script or job)

Rails' own Rails.error.report and Rails.error.handle reach Zharp too.

Options

Every option can be passed to Zharp.init or set in the environment.

Zharp.initEnvironmentDefault
key:ZHARP_KEY (Rails: then credentials.zharp.key)— nothing is sent without one
service:ZHARP_SERVICE, OTEL_SERVICE_NAMEthe Rails app's name, else the project folder
environment:ZHARP_ENVIRONMENTRails.env
release:ZHARP_RELEASE—
endpoint:ZHARP_ENDPOINThttps://api.zharp.io/api/v1/otlp
sample_rate:ZHARP_SAMPLE_RATE1.0 (errors are always sent)
logs:ZHARP_LOGSfalse. See Logs.
log_correlation:ZHARP_LOG_CORRELATIONtrue: the trace_id=… span_id=… stamp
capture_headers:ZHARP_CAPTURE_HEADERSon; { redact: ["x-tenant"] } filters more names
capture_query_errors:ZHARP_CAPTURE_QUERY_ERRORStrue
capture_source_context:ZHARP_CAPTURE_SOURCE_CONTEXTtrue: the code that ran, with each error
capture_bodies:ZHARP_CAPTURE_BODIES (errors, all, off)off. See Request and response bodies.
tracing:ZHARP_TRACINGtrue; false sends errors and logs only
instrumentation:—options per OpenTelemetry instrumentation, by class name
—ZHARP_DISABLED=trueturns everything off
Zharp.init(instrumentation: {
  "OpenTelemetry::Instrumentation::Sidekiq" => { span_naming: :job_class },
})
  • Zharp.flush sends what's queued now — at the end of a script or a short job.

Supported versions

  • Ruby 3.3, 3.4 and 4.0 (what current OpenTelemetry Ruby supports).
  • Rails 7.1 and later.
  • Sidekiq 4.2.10 and later; Puma, Unicorn; Sinatra, Hanami, Roda, Grape and any Rack app.

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.
  • Puma in cluster mode with preload_app! prints "Detected 2 Thread(s) started in app boot": those are OpenTelemetry's export threads in the master process. It's harmless — each worker starts its own after the fork. Nothing needs changing.
  • Plain Ruby: is Zharp.init called after your gems are required? Libraries loaded later aren't traced.
  • Sidekiq outside Rails: is require "zharp/sidekiq" in the file passed to -r, not on the command line?

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.