boltZharp Docs
codeSDKs

Python

zharp sends your logging records and errors, traces every request a Django, FastAPI or Flask app handles, and times its outgoing calls and database queries.

info
zharp 0.2.0

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

It is built on the official OpenTelemetry SDK: zharp configures the exporter, resource, propagation and the logging bridge, and turns on the instrumentations for the libraries you have installed — Django, FastAPI, Flask, requests, httpx, psycopg, psycopg2 and SQLAlchemy. Any other OpenTelemetry instrumentation you add is sent too.

Install

pip install zharp

Initialize

Call zharp.init() once, before your framework starts, so it can instrument the framework as it loads. Copy the key from the app's setup page in Applications.

import zharp

zharp.init(
    key="zpk_…",
    service="checkout-api",
    environment="production",
)

Leave arguments out to read them from the environment — the better place for a key on a server:

ZHARP_KEY=zpk_…
ZHARP_SERVICE=checkout-api
ZHARP_ENVIRONMENT=production
ZHARP_RELEASE=api@2.3.0     # optional
import zharp

zharp.init()   # reads ZHARP_* from the environment

init() never raises. Without a key it prints one line and sends nothing.

Django

At the top of manage.py, and of wsgi.py or asgi.py — whichever your server runs:

# manage.py — and the same two lines at the top of wsgi.py or asgi.py
import zharp

zharp.init()

import os
import sys
# … the rest of manage.py as it was

FastAPI

At the top of the module that creates the app, before FastAPI():

# main.py
import zharp

zharp.init()

from fastapi import FastAPI

app = FastAPI()

Flask

At the top of the module that creates the app, before Flask(__name__):

# app.py
import zharp

zharp.init()

from flask import Flask

app = Flask(__name__)

Logs

Every line your app logs or prints during a request — logging, print, loguru, structlog — ends with the request's ids: trace_id=… span_id=… (two fields in a JSON line). Where the Zharp agent reads your app's output, it brings those lines in and Zharp links each one to its request — one copy, nothing sent twice. log_correlation=False turns the stamp off.

Where nothing reads the output — serverless, a host without the agent — pass logs=True (or set ZHARP_LOGS=true) and the SDK sends them itself: logging records at INFO and above (change it with logging_level), loguru, structlog and everything printed, each with its trace and the request's user. Errors and zharp.log are always sent:

import logging

log = logging.getLogger("shop.checkout")
log.warning("Stock low for %s", sku)          # sent, with the request's trace and user

zharp.log.info("Order placed", {"order_id": 42})   # or straight to Zharp: debug, info, warn, error, fatal

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.

import zharp

zharp.init(key="zpk_…", service="checkout-api", tracing=False)

Or leave the code as it is and set ZHARP_TRACING=false 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

  • An exception that escapes a request, ends the program or ends a thread is reported as unhandled, with the request's trace.
  • logger.exception(...) reports the exception too.
  • Each exception is reported once, even when both the instrumentation and the framework's logger see it.
try:
    charge(order)
except PaymentError as e:
    zharp.capture_error(e, {"order_id": order.id})   # reported as handled

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 becomes a span, continuing the caller's trace from traceparent, with spans for outgoing requests and httpx calls and database queries under it.

with zharp.start_span("render invoice"):    # a span around some work
    render(invoice)

zharp.set_tag("region", "eu-west")          # on every span and log after

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 Django, Flask and FastAPI, and outgoing calls made with requests and httpx.

# failed requests only; "all" for every one
zharp.init(key="zpk_…", service="checkout-api", capture_bodies="errors")

# or ZHARP_CAPTURE_BODIES=errors in the environment, or, with more control:
from zharp import CaptureBodies

zharp.init(capture_bodies=CaptureBodies(
    mode="all",
    max_size=65536,
    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.
  • Gzip and deflate bodies are inflated first.
  • A response your code streams — requests with stream=True, and every httpx response — is read after its span has ended, so it shows as [stream · application/json · 60 B] rather than its text.
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 and log of the request gets them with no code. When the server knows the user better:

zharp.set_user(id=user.id, email=user.email)   # for the rest of this request

Options

OptionEnvironmentDefault
capture_bodiesZHARP_CAPTURE_BODIESoff; "errors" or "all". See Request and response bodies.
keyZHARP_KEY— (nothing is sent without one)
serviceZHARP_SERVICE, OTEL_SERVICE_NAMEThe name in pyproject.toml
environmentZHARP_ENVIRONMENTnone
releaseZHARP_RELEASEnone
logsZHARP_LOGSFalse; True sends what the app logs and prints. See Logs.
log_correlationZHARP_LOG_CORRELATIONTrue: lines logged in a request end with trace_id=… span_id=…
tracingZHARP_TRACINGTrue; False is logs only
sample_rateZHARP_SAMPLE_RATE1.0 — share of traces kept; logs and errors are always sent
logging_levelZHARP_LOGGING_LEVELINFO; False leaves logging alone
capture_uncaught—True
instrument—True; False turns the automatic instrumentations off
—ZHARP_DISABLEDtrue starts nothing

Delivery

Telemetry is batched and sent every 5 seconds from a background thread, gzip-compressed, and what is left goes when the program exits. In a serverless function or at the end of a job, call zharp.flush().

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 zharp.init() called before the framework is imported and the app created? Otherwise requests may not be traced.

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.