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 asmeta.loggerand 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. Aprint()is not captured at all; onlyloggingrecords andlog.*calls are, so a worker that reports progress withprint()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.
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,sessionidand 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 ashttps://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 aSIGKILL.- 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 -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 uploadon an existing version fails, and--skip-existingonly hides it. Sotwine checkand 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.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| logerhub_client-0.2.0.tar.gz | 57.6 kB | Without provenance | Details for logerhub_client-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| logerhub_client-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for logerhub_client-0.2.0-py3-none-any.whl |
Total release size: 95.8 kB
Release files / logerhub_client-0.2.0.tar.gz
| Download URL | logerhub_client-0.2.0.tar.gz |
|---|---|
| Size | 57.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fd1fb10cf6e5eefd61b9bc945968bc4e8d406d86b1aebc2c8b792f35dfb91136
|
|
BLAKE2b-256 checksum How to use checksums |
6f44596dee27f31d39d6e584f31584d8598a30a3a2d06d6da56905e04cb574e5
|
| 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.2.0-py3-none-any.whl
| Download URL | logerhub_client-0.2.0-py3-none-any.whl |
|---|---|
| Size | 38.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
279056f7a0a3cecdabc2b893ca83e17da6f368822e2636838b7b35cc696a4699
|
|
BLAKE2b-256 checksum How to use checksums |
62f9d9b02556aa46aabaea6f7de4e2378c93b07ee22998a65db7abba06e39dce
|
| 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.2.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.