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

One global client, then a handle per job

The shape a worker fleet wants. init() once at startup, and every component reaches the client without being handed it:

import logerhub

logerhub.init(                      # once, at startup
    url="wss://logs.example.com/v1/stream",
    api_key="lgb_live_…",
    service="ota-sync",
    env="prod",
    spool="/var/lib/ota-sync/logerhub",
)

job = logerhub.task(work_item_id)   # or logerhub.job(...) — same function
job.info("Starting work item", meta={"param": param})
...
job.info(
    f"Finished Task {work_item_id} with result {result}",
    meta={"task": {"ok": result == 0, "result": result, "duration_ms": elapsed_ms}},
)

logerhub.task() is not a new type — it is the child logger with task_id already filled in, so every line it writes groups into one row on the console's Tasks page. Declaring the outcome stays the job's own meta.task, because only the job knows it.

The reason to go through a global rather than passing the logger: the job's id is known at the top of a worker loop, while the lines come from components several calls down that have no business taking a logger parameter. They call logerhub.get() or logerhub.task(id).

def upload_availability(property_id):          # no logger parameter
    logerhub.get().info(f"Upload Availability for Property = {property_id}")

Calling init() twice keeps the first logger and reports the second — closing a live one out from under whatever already holds it would drop the lines in its queue. Pass replace=True if you mean it. A log call made before init() is discarded with one line on stderr saying so: raising would take a worker down at its first log line for a startup mistake, and discarding quietly is the failure this client exists to avoid.

Or an explicit logger

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 = logerhub.task("nightly-import")       # or log.task(…) on an explicit logger
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.

Getting the id onto a component's lines

The global reaches the client, not the current job. This is the one trap worth knowing:

def upload_availability(property_id):
    logerhub.get().info(f"Upload Availability for Property = {property_id}")
    #            ^ reaches the gateway, carries NO task_id, groups with nothing

The job's id lives on the handle, not on the client, so a component calling get() writes a line that belongs to no task. It is not lost — it is in the explorer, in the live tail, counted in usage — but it will not appear in its job's row, and the Tasks page will show a job of three lines where the work actually produced seven.

The id is known at the top of the worker loop while those lines come from functions several calls down. Three ways to bridge it, in the order they cost you:

# 1. Pass the handle. Explicit, nothing hidden, and it touches every signature.
job = logerhub.task(work_item_id)
upload_availability(communicator, job)
# 2. Through `logging`, per call: one keyword, no signature changes, but every call site
#    that matters has to remember it.
logging.getLogger("SLMWebsiteProcessor").info("Starting work item", extra={"task_id": wid})
# 3. Hold it in a contextvar of your own, which is what the library does not do for you
#    yet. Set once per job; read wherever you log.
import contextvars
current_job = contextvars.ContextVar("current_job", default=None)

def log_here():
    return current_job.get() or logerhub.get()

# in the worker loop
token = current_job.set(logerhub.task(work_item_id))
try:
    ...                      # every component below calls log_here()
finally:
    current_job.reset(token)

A contextvars.ContextVar is the right tool for this in Python: it is per-thread and per-async-task, so a threaded worker pool and an asyncio loop both behave. One catch — with a thread or process pool, set it inside the worker function; context does not cross into pool threads on its own.

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={"task": {"ok": …}} on the finish line makes "which jobs failed" a query instead of a read — see below. A print() is not captured at all; only logging records and log.* calls are, so a worker that reports progress with print() reports it to nobody.

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.

Console verbosity, from the environment

Start the app with a level and you get a filtered local echo, with no code change:

DEBUG=6 python worker.py        # info and higher on the terminal
DEBUG=4 python worker.py        # warnings and worse
DEBUG=7 python worker.py        # everything, debug included
DEBUG=off python worker.py      # nothing locally

It is the syslog scale — 0 emerg … 7 debug, a higher number meaning more output — because it is the only standard one, and names work too:

DEBUG Shows
7 debug, info, warn, error, fatal everything
6 info, warn, error, fatal the usual choice
4 warn, error, fatal
3 error, fatal
2 and below fatal
info, warn, error, fatal, debug from that level up warning and critical also work
true, 1, off, false, 0, … ignored see below

5 excludes info. syslog's 5 is notice, which it ranks above info — faithful to the standard and the one value on the scale that surprises people. Use 6.

Only the terminal is filtered. The gateway still gets every line. That is the point of having one: the terminal is for whoever is watching it now, and the archive is for the question nobody has asked yet. There is no setting here that drops lines from LogerHUB.

DEBUG is not this library's variable

Half the Python world sets DEBUG as a boolean — Django's is the obvious one — and that value is addressed to that framework. If this library read DEBUG=True as "verbosity 7", an app that merely has Django's setting in its environment would start echoing every line, with its dimensions and metadata, to stderr: a second destination for the data that nobody chose.

So from the bare DEBUG, only an unambiguous level is accepted — a level name, or a number from 2 to 7. Anything boolean-looking (true, false, yes, no, on, off, 0, 1) is treated as somebody else's and leaves the console alone.

DEBUG=6                       # read: info and higher
DEBUG=info                    # read
DEBUG=True                    # ignored, console stays off
LOGERHUB_CONSOLE_LEVEL=true   # everything — this name can only be ours
LOGERHUB_CONSOLE_LEVEL=off    # explicitly nothing
LOGERHUB_CONSOLE_LEVEL=fatal  # the fatal-only console DEBUG=1 can no longer reach

LOGERHUB_CONSOLE_LEVEL is checked first and takes any value, including the booleans, because that name can only have been set for this. It is the one to use in a deploy file that already carries a DEBUG.

In code, either explicitly:

logerhub.init(..., console=True, console_level="info")   # beats the environment
logerhub.init(..., console=False)                         # never echoes, whatever DEBUG says

Left unset, console follows the environment; console=True without a level still prints everything, as it did before this existed.

Colour

On by default when stderr is a terminal, with raw ANSI escapes — no extra package. The level is painted, the timestamp and dimensions are dimmed, and the message keeps the terminal's own colour so it stays the thing your eye lands on. Painting everything would leave nothing emphasised.

The codes are the ones the TypeScript client uses, so a Node service and a Python worker side by side read the same colour for the same severity:

debug magenta
info cyan
warn bright yellow
error, fatal red

The conventions, in the order they override each other:

NO_COLOR=1      # off, whatever else says — no-color.org
FORCE_COLOR=1   # on where the TTY check says no: CI logs and `docker logs` do render it
TERM=dumb       # off

Otherwise it follows stderr.isatty(): redirected to a file, escape codes are garbage somebody has to grep around. console_color=True or False in code settles it outright. The check runs once when the logger is built, since isatty() is a syscall and the answer cannot change for the life of the process.

Choosing what reaches the gateway

Separate from the console, and a much heavier setting: a line below this threshold is gone. Not echoed somewhere else, not in the archive.

logerhub.init(..., level="info")       # debug never leaves the process
LOGERHUB_LEVEL=info python worker.py

Same scale and names as the console. DEBUG is deliberately not read for this one — a variable half the ecosystem sets for its own reasons must not decide what this process keeps.

Through logging you already had this, and nothing here replaces it:

logging.getLogger().addHandler(LogerHubHandler(log, level=logging.INFO))

A handler's level stops a record before it ever reaches this client, as do the logger's own level and any addFilter. What had no filter was the native path — log.debug(...) called directly, which never goes near logging — and neither path could be set from the environment. level= covers both uniformly.

The default sends everything, because a logging client should not quietly decide what is not worth keeping. A line this filter drops is not counted in droppedSinceLast: that number means "the queue overflowed and lines were lost", which is worth acting on, and folding a configured filter into it would make it meaningless.

The two thresholds compose, which is the useful part:

LOGERHUB_LEVEL=info DEBUG=7 python worker.py   # all of it locally, info and up archived

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
level everything threshold for what reaches the gateway; below it the line is gone
console follows DEBUG echo to stderr; True/False overrides the environment
console_level from DEBUG the syslog threshold for that echo
console_color TTY detection ANSI colour; honours NO_COLOR and FORCE_COLOR
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 -r testpypi dist/*    # rehearse
twine upload dist/*                # the real thing

testpypi there is a literal, not a stand-in for your own value: twine special-cases exactly two repository names, pypi (the default) and testpypi, and knows their upload URLs without any configuration. Any other name has to exist as a section in ~/.pypirc or twine refuses with "Missing '' section" — that is how a private index is named. To skip the config entirely, give the URL: --repository-url https://test.pypi.org/legacy/.

The username is the literal __token__ and the password is an API token. Both repositories read credentials the same way — a ~/.pypirc section, TWINE_USERNAME/TWINE_PASSWORD, or an interactive prompt:

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

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

Two sections because TestPyPI accounts are entirely separate from PyPI ones — a different registration, and a token from one is rejected by the other.

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.4.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.4.0
File Size Uploaded Provenance Actions
logerhub_client-0.4.0.tar.gz 68.3 kB Without provenance Details for logerhub_client-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 112.6 kB

Release files / logerhub_client-0.4.0.tar.gz

Download URL logerhub_client-0.4.0.tar.gz
Size 68.3 kB
Tags Source
SHA-256 checksum
How to use checksums
204724cd6942322c68ee0963ef8ac9dab4b47a791ddc493380a5948e5bfa3c4e
BLAKE2b-256 checksum
How to use checksums
61c2acdccc9df869a3b2543f6e985daed1f44b67d54406ee98f496393cfc08db
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.4.0-py3-none-any.whl

Download URL logerhub_client-0.4.0-py3-none-any.whl
Size 44.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
17d9db2fbce0b00042537bfae2d96ec2d0e203b7c258c4636967e81d234f9b45
BLAKE2b-256 checksum
How to use checksums
3dff1153187dabbdb68407835b224eadd70ee93ef7d30bd13d1aace503d07355
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.4.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