Skip to main content

logerhub-client

Stream structured logs from Python to a LogerHUB gateway: batched, spooled to disk, redacted before they leave the process.

pip install logerhub-client

Python 3.10+. One dependency (websocket-client), which has none of its own.

Quick start

from logerhub import create_logger

log = create_logger(
    url="wss://logs.example.com/v1/stream",
    api_key="lgb_live_…",
    service="billing",
    env="prod",
    spool="/var/lib/billing/logerhub",   # survive a restart
)

log.info("charge captured", dims={"company_id": "acme"}, meta={"amount_cents": 1200})

Nothing connects until the first entry. log.close() drains what is queued; undelivered batches go to the spool for the next process.

Or through logging, with no call site rewritten

import logging
from logerhub import LogerHubHandler, create_logger

log = create_logger(url=…, api_key=…, service="billing", env="prod")
logging.getLogger().addHandler(LogerHubHandler(log))

logging.getLogger("billing.invoices").info("charged %s cents", 1200)

The record's logger name arrives as meta.logger, exc_info as meta.error with its stack, and extra={"dims": …, "meta": …} as those fields. Other extra keys are ignored — extra is your namespace, and a library may attach anything to it.

Grouping a job's lines

Set task_id and the console groups them: every line of one import run, one nightly job, one queue message.

job = log.child(dims={"task_id": "nightly-import"})
job.info("started", meta={"source": "s3://bucket/feed.csv"})
job.warning("3 rows skipped")
job.info("finished", meta={"rows": 10_412})
logging.getLogger("importer").info("started", extra={"task_id": "nightly-import"})

Every one of those lines becomes a row on the console's Tasks page: when the job started, when it ended, how long it took, how many lines it wrote, which components took part, and whether anything failed. Clicking a row gives you that job's lines, in order. task:nightly-import is the same thing as a query, and the inspector's Related tab links from any single line to all the others sharing the id.

Started and Ended are the first and last line logged under the id — for a worker that logs a start and a finish, those are the job's own bounds; for one that does not, they are bounds on it.

trace_id works identically and is the one to use when the work crosses services: a trace spans services, a task is one unit of work's own lines.

Making a task row worth reading

The task id is usually known at the top of a worker loop, while the lines come from components further down that have no idea a job exists. Two ways to bridge that:

# Pass the child logger down. Explicit, and it touches every component signature.
job = log.child(dims={"task_id": str(work_item_id)})
upload_availability(communicator, job)
# Or, through `logging`, per call — no plumbing, one keyword.
logging.getLogger("SLMWebsiteProcessor").info("Starting work item", extra={"task_id": wid})

Two more things that turn a row from "10 lines" into something you can act on:

  • Use the component as the logger name. logging.getLogger("SLMWebsiteProcessor") arrives as meta.logger and fills the Tasks page's Components column; baked into the message string it is only free-text searchable.
  • Put the outcome in meta. meta={"result": 0} on the finish line makes "which jobs failed" a query instead of a read. A print() is not captured at all — only logging records and log.* calls are.

Saying whether a task failed

The Tasks page shows an outcome per job, and the only reliable source for it is the job itself. Put it on the finish line:

job = log.child(dims={"task_id": str(work_item_id)})
job.info("Starting work item", meta={"param": 3557898})
...
job.info(
    f"Finished Task {work_item_id} with result {result}",
    meta={"task": {"ok": result == 0, "result": result, "duration_ms": elapsed_ms}},
)
Field
ok True/False. The one that decides the column.
result Whatever your worker calls it — 0, 1, "skipped". Shown next to the outcome.
status A string alternative to ok; ok/success/succeeded read as success, anything else as failure.
duration_ms The job's own measure, preferred over the gap between its first and last line.

Why not just log the failure at error level? Because most workers do not. A line reading Info[SystaskObject] Finished Task 10464854 with result 1 is a failed job logged at info, and anything inferring the outcome from log levels calls it a success. LogerHUB made that exact substitution once already — the old HTTP success rate used log level and counted a 500 logged at info as a win — which is why the page asks the job instead.

Without a declared outcome a task reads errored if any line was logged at error level, and “said nothing” otherwise — deliberately not succeeded, because a job that never reported has only not complained. ok:false in the explorer finds exactly the jobs that reported failing.

Showing why it failed

A row that says "failed" and nothing else sends you to the lines to find out why. Log the exception and the reason appears on the row itself:

try:
    upload_availability(property_id)
except Exception:
    job.exception("Upload Availability failed")   # type, message and stack
    job.info("Finished Task", meta={"task": {"ok": False, "result": 1}})

log.exception() and the logging handler's exc_info both write meta.error = {type, message, stack}, which the Tasks page reads into its Why column: ConnectionResetError: the OTA closed the connection. The stack stays in the entry for when you open it.

A logged exception alone marks the task errored, not failed — a job can throw, catch, retry and finish fine, so only meta.task.ok settles it. Both together is the useful combination: the outcome says what happened, the exception says why.

A job that finished but runs again

A polling worker's job is usually not finished-and-done but finished-and-queued-again. Say when, and the Tasks page shows it in a Next run column:

job.info(
    f"Finished Task {wid} with result {result} and reschedule at {next_run}",
    meta={"task": {
        "ok": result == 0,
        "result": result,
        "duration_ms": elapsed_ms,
        "reschedule_at": next_run.isoformat(),   # or reschedule_s: 600
    }},
)

reschedule_at takes an ISO timestamp, epoch milliseconds or epoch seconds. reschedule_s is the other spelling, for a worker that only knows "in N seconds" — the page turns it into a time measured from the line that said it.

It is deliberately not part of the outcome. This run can have succeeded and another still be due; folding the two together would lose the only part anyone asks about when a queue stops draining. A next-run time already in the past shows amber: it may mean the scheduler is behind, or simply that the next run came back under a different task_id, which the console cannot tell apart.

Levels

Python's names and the wire's differ, so both spellings work and map to one wire level:

You write Arrives as
debug debug
info info
warn, warning warn
error, exception error
fatal, critical fatal

Through the handler, a level between the standard ones rounds down: 25 (the usual custom NOTICE) is an info, not a warn. Claiming a severity the application did not is worse than under-reporting it. An unrecognised level name becomes info rather than costing the line.

Redaction

Values in meta are redacted on your thread, before the entry is queued — so a dict you keep mutating afterwards cannot change what was sent, and no secret waits in a queue to be scrubbed.

  • By key: password, token, secret, apikey, authorization, cookie, cvv, ssn, jwt, sessionid and similar, at any depth, case- and separator-insensitive. redact_keys=[…] extends the list; it never replaces it.
  • By url value: {"redirect_uri": "https://app/cb?code=…"} arrives as https://app/cb. A url is the one place a credential hides where no key name betrays it. A url with nothing to remove is kept byte-for-byte, so an untrimmed one is the whole url.

Anything JSON cannot hold degrades rather than raising: set → list, bytes → [bytes 12], Decimal → string, datetime → ISO, a cycle → [circular], anything else → repr. A logging call must not be able to take your program down, and someone will put a set in meta.

Values over max_meta_bytes (8192) are replaced by a marker that still reports the original size.

The spool

Without spool= the client holds undelivered batches in memory only, bounded by batch_max_queue (10,000), dropping oldest first and reporting the count to the gateway — a drop is allowed, a silent drop is not.

With spool="/var/lib/app/logerhub":

  • Bounds: 256 MB and 7 days, oldest pruned first. One batch bigger than the budget is kept, because it is still the only thing you have.
  • spool_mode="on-failure" (default) touches the disk only while the gateway is unreachable. "always" writes every batch first, costing an I/O per batch and buying durability across a SIGKILL.
  • A corrupt spool file is moved aside and replaced, reported, not fatal.

Never point a Python and a Node client at the same spool directory. The format is identical, which is why they would both claim the same rows and send them twice.

Threads, and fork

One background thread, started on the first entry. log.info() enqueues and returns; the network, the disk and the retries all happen off your thread. Safe from any number of threads, and from async code — no event loop required.

Create the logger before you fork; log after. That is what gunicorn --preload, uWSGI and Celery do, and it is the supported shape. The thread starts lazily precisely so that a parent which has not logged yet has no thread for a child to inherit.

If the parent has logged before forking, the child may deadlock on its first network call. This is not a bug in this library — a plain websocket.create_connection in such a child hangs too, because a lock inside libc is held by a thread the child does not have, which is what CPython's own DeprecationWarning: This process is multi-threaded, use of fork() may lead to deadlocks in the child is about. No Python code can release it. The client detects the situation and reports one actionable line through on_error; to avoid it, either do not log before forking, or call log.close() in the parent first.

TLS

Verified by default. For a private CA — make cert in the LogerHUB repo produces one:

create_logger(…, ca_file="/etc/ssl/certs/internal-ca.pem")

tls_verify=False exists and should be a last resort: anyone on the network path can then read every log line and forge new ones. Prefer ca_file.

Options

Option Default
url, api_key, service, env — required
dims {} stamped on every entry
instance hostname the replica identity; False omits it
spool, spool_mode None, on-failure see above
spool_max_bytes, spool_max_age_ms 256 MB, 7 days
redact_keys () extends the defaults
max_meta_bytes 8192
batch_max_entries, batch_max_ms, batch_max_queue 500, 1000, 10000
tls_verify, ca_file True, None
console False echo entries to stderr
on_error rate-limited stderr every internal failure
register_atexit True flush on an orderly exit

console writes to stderr, not stdout: a CLI's stdout is its output and a stdio MCP server's is its protocol stream.

Instance identity

Every entry carries an instance dimension, defaulting to socket.gethostname() — inside a container, the container id. It is what the console's Instances page is built on, and what answers "which replica?" without per-call-site configuration. instance=False opts out; a dims={"instance": …} you set yourself wins.

Not here yet

HTTP request logging, MCP tool calls and WebSocket instrumentation are in the TypeScript client only. This package does standard log lines, deliberately — ask if you need the others.

Failure behaviour

What happens What the client does
Gateway unreachable Queues, then spools. Reconnects with jittered backoff to 30s.
Gateway nacks retryably Returns the batch to the spool and retries.
Gateway nacks terminally Drops the batch and reports it. Retrying a verdict is an infinite loop.
No ack within 30s Treats it as a retryable failure.
Queue full, no spool Drops oldest, counts it, tells the gateway on the next batch.
Anything raises internally Goes to on_error. Never to your call site.

Development

uv venv .venv && VIRTUAL_ENV=.venv uv pip install -e '.[dev]'
.venv/bin/pytest tests -q

tests/test_ts_agreement.py reads the TypeScript source and fails when the wire constants or the redaction lists drift from it. The suite runs on 3.10 and 3.14; verify.mjs at the repo root runs this client against a real gateway.

Releasing

cd packages/python-client
uv pip install -e '.[publish]'

rm -rf dist && uv build            # or: python -m build
twine check dist/*                 # catches a README PyPI will not render
twine upload --repository testpypi dist/*    # rehearse
twine upload dist/*                # the real thing

The username is the literal __token__ and the password is a PyPI API token, or put them in ~/.pypirc:

[pypi]
  username = __token__
  password = pypi-...

Two things that make this a one-way door:

  • A version can never be re-uploaded. Not replaced, not deleted. A mistake in 0.1.0 means publishing 0.1.1; twine upload on an existing version fails, and --skip-existing only hides it. So twine check and a TestPyPI rehearsal first.
  • The name is claimed on first publish and a project cannot be renamed.

On TestPyPI, install with --extra-index-url https://pypi.org/simple/ as well — websocket-client is not mirrored there.

In CI, prefer Trusted Publishing over a stored token: pypa/gh-action-pypi-publish runs twine for you against a short-lived OIDC credential, so there is nothing in the repository to leak.

Metadata

Release files for logerhub-client 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logerhub-client 0.1.0
File Size Uploaded Provenance Actions
logerhub_client-0.1.0.tar.gz 52.0 kB Without provenance Details for logerhub_client-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logerhub-client 0.1.0
File Interpreter ABI Platform Actions
logerhub_client-0.1.0-py3-none-any.whl Python 3 none any Details for logerhub_client-0.1.0-py3-none-any.whl

Total release size: 87.1 kB

Release files / logerhub_client-0.1.0.tar.gz

Download URL logerhub_client-0.1.0.tar.gz
Size 52.0 kB
Tags Source
SHA-256 checksum
How to use checksums
7e905f89025d89bd4c766cb35689f2e9426a250111a047e982a344bc25296f0b
BLAKE2b-256 checksum
How to use checksums
9cdf3976e9e6fe215e8d8eaaf73af3637e8ec13ab8046c8949e170a8b859a8d0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / logerhub_client-0.1.0-py3-none-any.whl

Download URL logerhub_client-0.1.0-py3-none-any.whl
Size 35.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
26c8c79b22d4d8c609de08de5876e70fc5bbb91a812ddf621779a94af616cc55
BLAKE2b-256 checksum
How to use checksums
235d87253da12c36e725fc8a41ad358e112519e4be65083903d912a813d3c52a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Security for logerhub-client 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page