logerhub-client 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- logerhub_client-0.1.0/.gitignore +7 -0
- logerhub_client-0.1.0/LICENSE +21 -0
- logerhub_client-0.1.0/PKG-INFO +327 -0
- logerhub_client-0.1.0/README.md +299 -0
- logerhub_client-0.1.0/examples/basic.py +42 -0
- logerhub_client-0.1.0/pyproject.toml +53 -0
- logerhub_client-0.1.0/src/logerhub/__init__.py +26 -0
- logerhub_client-0.1.0/src/logerhub/batcher.py +133 -0
- logerhub_client-0.1.0/src/logerhub/console.py +45 -0
- logerhub_client-0.1.0/src/logerhub/handler.py +126 -0
- logerhub_client-0.1.0/src/logerhub/logger.py +545 -0
- logerhub_client-0.1.0/src/logerhub/protocol.py +125 -0
- logerhub_client-0.1.0/src/logerhub/py.typed +0 -0
- logerhub_client-0.1.0/src/logerhub/redact.py +216 -0
- logerhub_client-0.1.0/src/logerhub/spool.py +287 -0
- logerhub_client-0.1.0/src/logerhub/transport.py +324 -0
- logerhub_client-0.1.0/tests/stub_gateway.py +196 -0
- logerhub_client-0.1.0/tests/test_batcher.py +177 -0
- logerhub_client-0.1.0/tests/test_fork.py +249 -0
- logerhub_client-0.1.0/tests/test_handler.py +219 -0
- logerhub_client-0.1.0/tests/test_logger.py +369 -0
- logerhub_client-0.1.0/tests/test_protocol.py +80 -0
- logerhub_client-0.1.0/tests/test_redact.py +226 -0
- logerhub_client-0.1.0/tests/test_spool.py +188 -0
- logerhub_client-0.1.0/tests/test_transport.py +283 -0
- logerhub_client-0.1.0/tests/test_ts_agreement.py +50 -0
- logerhub_client-0.1.0/tests/ts_source.py +63 -0
- logerhub_client-0.1.0/verify_push.py +24 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Leviathan Systems
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: logerhub-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Stream structured logs to a LogerHUB gateway: batched, spooled to disk, redacted before they leave the process.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Lanpingner/LogerHUB/tree/main/packages/python-client#readme
|
|
6
|
+
Project-URL: Repository, https://github.com/Lanpingner/LogerHUB
|
|
7
|
+
Project-URL: Issues, https://github.com/Lanpingner/LogerHUB/issues
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: logerhub,logging,loki,observability
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: System :: Logging
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: websocket-client>=1.7
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
23
|
+
Requires-Dist: websockets>=12; extra == 'dev'
|
|
24
|
+
Provides-Extra: publish
|
|
25
|
+
Requires-Dist: build>=1.2; extra == 'publish'
|
|
26
|
+
Requires-Dist: twine>=5; extra == 'publish'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# logerhub-client
|
|
30
|
+
|
|
31
|
+
Stream structured logs from Python to a [LogerHUB](https://github.com/Lanpingner/LogerHUB) gateway: batched, spooled to disk, redacted before they leave the process.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install logerhub-client
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Python 3.10+. One dependency (`websocket-client`), which has none of its own.
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from logerhub import create_logger
|
|
43
|
+
|
|
44
|
+
log = create_logger(
|
|
45
|
+
url="wss://logs.example.com/v1/stream",
|
|
46
|
+
api_key="lgb_live_…",
|
|
47
|
+
service="billing",
|
|
48
|
+
env="prod",
|
|
49
|
+
spool="/var/lib/billing/logerhub", # survive a restart
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
log.info("charge captured", dims={"company_id": "acme"}, meta={"amount_cents": 1200})
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Nothing connects until the first entry. `log.close()` drains what is queued; undelivered batches go to the spool for the next process.
|
|
56
|
+
|
|
57
|
+
### Or through `logging`, with no call site rewritten
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import logging
|
|
61
|
+
from logerhub import LogerHubHandler, create_logger
|
|
62
|
+
|
|
63
|
+
log = create_logger(url=…, api_key=…, service="billing", env="prod")
|
|
64
|
+
logging.getLogger().addHandler(LogerHubHandler(log))
|
|
65
|
+
|
|
66
|
+
logging.getLogger("billing.invoices").info("charged %s cents", 1200)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
## Grouping a job's lines
|
|
72
|
+
|
|
73
|
+
Set `task_id` and the console groups them: every line of one import run, one nightly job, one queue message.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
job = log.child(dims={"task_id": "nightly-import"})
|
|
77
|
+
job.info("started", meta={"source": "s3://bucket/feed.csv"})
|
|
78
|
+
job.warning("3 rows skipped")
|
|
79
|
+
job.info("finished", meta={"rows": 10_412})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
logging.getLogger("importer").info("started", extra={"task_id": "nightly-import"})
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
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.
|
|
87
|
+
|
|
88
|
+
**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.
|
|
89
|
+
|
|
90
|
+
`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.
|
|
91
|
+
|
|
92
|
+
### Making a task row worth reading
|
|
93
|
+
|
|
94
|
+
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:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
# Pass the child logger down. Explicit, and it touches every component signature.
|
|
98
|
+
job = log.child(dims={"task_id": str(work_item_id)})
|
|
99
|
+
upload_availability(communicator, job)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
# Or, through `logging`, per call — no plumbing, one keyword.
|
|
104
|
+
logging.getLogger("SLMWebsiteProcessor").info("Starting work item", extra={"task_id": wid})
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Two more things that turn a row from "10 lines" into something you can act on:
|
|
108
|
+
|
|
109
|
+
- **Use the component as the logger name.** `logging.getLogger("SLMWebsiteProcessor")`
|
|
110
|
+
arrives as `meta.logger` and fills the Tasks page's Components column; baked into the
|
|
111
|
+
message string it is only free-text searchable.
|
|
112
|
+
- **Put the outcome in `meta`.** `meta={"result": 0}` on the finish line makes "which jobs
|
|
113
|
+
failed" a query instead of a read. A `print()` is not captured at all — only `logging`
|
|
114
|
+
records and `log.*` calls are.
|
|
115
|
+
|
|
116
|
+
### Saying whether a task failed
|
|
117
|
+
|
|
118
|
+
The Tasks page shows an outcome per job, and the only reliable source for it is the job
|
|
119
|
+
itself. Put it on the finish line:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
job = log.child(dims={"task_id": str(work_item_id)})
|
|
123
|
+
job.info("Starting work item", meta={"param": 3557898})
|
|
124
|
+
...
|
|
125
|
+
job.info(
|
|
126
|
+
f"Finished Task {work_item_id} with result {result}",
|
|
127
|
+
meta={"task": {"ok": result == 0, "result": result, "duration_ms": elapsed_ms}},
|
|
128
|
+
)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
| Field | |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `ok` | `True`/`False`. The one that decides the column. |
|
|
134
|
+
| `result` | Whatever your worker calls it — `0`, `1`, `"skipped"`. Shown next to the outcome. |
|
|
135
|
+
| `status` | A string alternative to `ok`; `ok`/`success`/`succeeded` read as success, anything else as failure. |
|
|
136
|
+
| `duration_ms` | The job's own measure, preferred over the gap between its first and last line. |
|
|
137
|
+
|
|
138
|
+
**Why not just log the failure at `error` level?** Because most workers do not. A line
|
|
139
|
+
reading `Info[SystaskObject] Finished Task 10464854 with result 1` is a failed job logged
|
|
140
|
+
at info, and anything inferring the outcome from log levels calls it a success. LogerHUB
|
|
141
|
+
made that exact substitution once already — the old HTTP success rate used log level and
|
|
142
|
+
counted a 500 logged at info as a win — which is why the page asks the job instead.
|
|
143
|
+
|
|
144
|
+
Without a declared outcome a task reads **errored** if any line was logged at error level,
|
|
145
|
+
and **“said nothing”** otherwise — deliberately not *succeeded*, because a job that never
|
|
146
|
+
reported has only not complained. `ok:false` in the explorer finds exactly the jobs that
|
|
147
|
+
reported failing.
|
|
148
|
+
|
|
149
|
+
### Showing why it failed
|
|
150
|
+
|
|
151
|
+
A row that says "failed" and nothing else sends you to the lines to find out why. Log the
|
|
152
|
+
exception and the reason appears on the row itself:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
try:
|
|
156
|
+
upload_availability(property_id)
|
|
157
|
+
except Exception:
|
|
158
|
+
job.exception("Upload Availability failed") # type, message and stack
|
|
159
|
+
job.info("Finished Task", meta={"task": {"ok": False, "result": 1}})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`log.exception()` and the `logging` handler's `exc_info` both write
|
|
163
|
+
`meta.error = {type, message, stack}`, which the Tasks page reads into its **Why** column:
|
|
164
|
+
`ConnectionResetError: the OTA closed the connection`. The stack stays in the entry for
|
|
165
|
+
when you open it.
|
|
166
|
+
|
|
167
|
+
A logged exception alone marks the task **errored**, not failed — a job can throw, catch,
|
|
168
|
+
retry and finish fine, so only `meta.task.ok` settles it. Both together is the useful
|
|
169
|
+
combination: the outcome says what happened, the exception says why.
|
|
170
|
+
|
|
171
|
+
### A job that finished but runs again
|
|
172
|
+
|
|
173
|
+
A polling worker's job is usually not finished-and-done but finished-and-queued-again. Say
|
|
174
|
+
when, and the Tasks page shows it in a **Next run** column:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
job.info(
|
|
178
|
+
f"Finished Task {wid} with result {result} and reschedule at {next_run}",
|
|
179
|
+
meta={"task": {
|
|
180
|
+
"ok": result == 0,
|
|
181
|
+
"result": result,
|
|
182
|
+
"duration_ms": elapsed_ms,
|
|
183
|
+
"reschedule_at": next_run.isoformat(), # or reschedule_s: 600
|
|
184
|
+
}},
|
|
185
|
+
)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`reschedule_at` takes an ISO timestamp, epoch milliseconds or epoch seconds.
|
|
189
|
+
`reschedule_s` is the other spelling, for a worker that only knows "in N seconds" — the
|
|
190
|
+
page turns it into a time measured from the line that said it.
|
|
191
|
+
|
|
192
|
+
**It is deliberately not part of the outcome.** This run can have succeeded *and* another
|
|
193
|
+
still be due; folding the two together would lose the only part anyone asks about when a
|
|
194
|
+
queue stops draining. A next-run time already in the past shows amber: it may mean the
|
|
195
|
+
scheduler is behind, or simply that the next run came back under a different `task_id`,
|
|
196
|
+
which the console cannot tell apart.
|
|
197
|
+
|
|
198
|
+
## Levels
|
|
199
|
+
|
|
200
|
+
Python's names and the wire's differ, so both spellings work and map to one wire level:
|
|
201
|
+
|
|
202
|
+
| You write | Arrives as |
|
|
203
|
+
|---|---|
|
|
204
|
+
| `debug` | `debug` |
|
|
205
|
+
| `info` | `info` |
|
|
206
|
+
| `warn`, `warning` | `warn` |
|
|
207
|
+
| `error`, `exception` | `error` |
|
|
208
|
+
| `fatal`, `critical` | `fatal` |
|
|
209
|
+
|
|
210
|
+
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.
|
|
211
|
+
|
|
212
|
+
## Redaction
|
|
213
|
+
|
|
214
|
+
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.
|
|
215
|
+
|
|
216
|
+
- **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.
|
|
217
|
+
- **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.
|
|
218
|
+
|
|
219
|
+
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`.
|
|
220
|
+
|
|
221
|
+
Values over `max_meta_bytes` (8192) are replaced by a marker that still reports the original size.
|
|
222
|
+
|
|
223
|
+
## The spool
|
|
224
|
+
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
With `spool="/var/lib/app/logerhub"`:
|
|
228
|
+
|
|
229
|
+
- **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.
|
|
230
|
+
- **`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`.
|
|
231
|
+
- A corrupt spool file is moved aside and replaced, reported, not fatal.
|
|
232
|
+
|
|
233
|
+
**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.
|
|
234
|
+
|
|
235
|
+
## Threads, and fork
|
|
236
|
+
|
|
237
|
+
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.
|
|
238
|
+
|
|
239
|
+
**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.
|
|
240
|
+
|
|
241
|
+
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.
|
|
242
|
+
|
|
243
|
+
## TLS
|
|
244
|
+
|
|
245
|
+
Verified by default. For a private CA — `make cert` in the LogerHUB repo produces one:
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
create_logger(…, ca_file="/etc/ssl/certs/internal-ca.pem")
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
`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`.
|
|
252
|
+
|
|
253
|
+
## Options
|
|
254
|
+
|
|
255
|
+
| Option | Default | |
|
|
256
|
+
|---|---|---|
|
|
257
|
+
| `url`, `api_key`, `service`, `env` | — | required |
|
|
258
|
+
| `dims` | `{}` | stamped on every entry |
|
|
259
|
+
| `instance` | hostname | the replica identity; `False` omits it |
|
|
260
|
+
| `spool`, `spool_mode` | `None`, `on-failure` | see above |
|
|
261
|
+
| `spool_max_bytes`, `spool_max_age_ms` | 256 MB, 7 days | |
|
|
262
|
+
| `redact_keys` | `()` | extends the defaults |
|
|
263
|
+
| `max_meta_bytes` | 8192 | |
|
|
264
|
+
| `batch_max_entries`, `batch_max_ms`, `batch_max_queue` | 500, 1000, 10000 | |
|
|
265
|
+
| `tls_verify`, `ca_file` | `True`, `None` | |
|
|
266
|
+
| `console` | `False` | echo entries to **stderr** |
|
|
267
|
+
| `on_error` | rate-limited stderr | every internal failure |
|
|
268
|
+
| `register_atexit` | `True` | flush on an orderly exit |
|
|
269
|
+
|
|
270
|
+
`console` writes to stderr, not stdout: a CLI's stdout is its output and a stdio MCP server's is its protocol stream.
|
|
271
|
+
|
|
272
|
+
## Instance identity
|
|
273
|
+
|
|
274
|
+
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.
|
|
275
|
+
|
|
276
|
+
## Not here yet
|
|
277
|
+
|
|
278
|
+
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.
|
|
279
|
+
|
|
280
|
+
## Failure behaviour
|
|
281
|
+
|
|
282
|
+
| What happens | What the client does |
|
|
283
|
+
|---|---|
|
|
284
|
+
| Gateway unreachable | Queues, then spools. Reconnects with jittered backoff to 30s. |
|
|
285
|
+
| Gateway nacks retryably | Returns the batch to the spool and retries. |
|
|
286
|
+
| Gateway nacks terminally | Drops the batch and reports it. Retrying a verdict is an infinite loop. |
|
|
287
|
+
| No ack within 30s | Treats it as a retryable failure. |
|
|
288
|
+
| Queue full, no spool | Drops oldest, counts it, tells the gateway on the next batch. |
|
|
289
|
+
| Anything raises internally | Goes to `on_error`. Never to your call site. |
|
|
290
|
+
|
|
291
|
+
## Development
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
uv venv .venv && VIRTUAL_ENV=.venv uv pip install -e '.[dev]'
|
|
295
|
+
.venv/bin/pytest tests -q
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
`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.
|
|
299
|
+
|
|
300
|
+
## Releasing
|
|
301
|
+
|
|
302
|
+
```bash
|
|
303
|
+
cd packages/python-client
|
|
304
|
+
uv pip install -e '.[publish]'
|
|
305
|
+
|
|
306
|
+
rm -rf dist && uv build # or: python -m build
|
|
307
|
+
twine check dist/* # catches a README PyPI will not render
|
|
308
|
+
twine upload --repository testpypi dist/* # rehearse
|
|
309
|
+
twine upload dist/* # the real thing
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
The username is the literal `__token__` and the password is a PyPI API token, or put them in `~/.pypirc`:
|
|
313
|
+
|
|
314
|
+
```ini
|
|
315
|
+
[pypi]
|
|
316
|
+
username = __token__
|
|
317
|
+
password = pypi-...
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Two things that make this a one-way door:
|
|
321
|
+
|
|
322
|
+
- **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.
|
|
323
|
+
- **The name is claimed on first publish** and a project cannot be renamed.
|
|
324
|
+
|
|
325
|
+
On TestPyPI, install with `--extra-index-url https://pypi.org/simple/` as well — `websocket-client` is not mirrored there.
|
|
326
|
+
|
|
327
|
+
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.
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
# logerhub-client
|
|
2
|
+
|
|
3
|
+
Stream structured logs from Python to a [LogerHUB](https://github.com/Lanpingner/LogerHUB) gateway: batched, spooled to disk, redacted before they leave the process.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install logerhub-client
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Python 3.10+. One dependency (`websocket-client`), which has none of its own.
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from logerhub import create_logger
|
|
15
|
+
|
|
16
|
+
log = create_logger(
|
|
17
|
+
url="wss://logs.example.com/v1/stream",
|
|
18
|
+
api_key="lgb_live_…",
|
|
19
|
+
service="billing",
|
|
20
|
+
env="prod",
|
|
21
|
+
spool="/var/lib/billing/logerhub", # survive a restart
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
log.info("charge captured", dims={"company_id": "acme"}, meta={"amount_cents": 1200})
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Nothing connects until the first entry. `log.close()` drains what is queued; undelivered batches go to the spool for the next process.
|
|
28
|
+
|
|
29
|
+
### Or through `logging`, with no call site rewritten
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import logging
|
|
33
|
+
from logerhub import LogerHubHandler, create_logger
|
|
34
|
+
|
|
35
|
+
log = create_logger(url=…, api_key=…, service="billing", env="prod")
|
|
36
|
+
logging.getLogger().addHandler(LogerHubHandler(log))
|
|
37
|
+
|
|
38
|
+
logging.getLogger("billing.invoices").info("charged %s cents", 1200)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
## Grouping a job's lines
|
|
44
|
+
|
|
45
|
+
Set `task_id` and the console groups them: every line of one import run, one nightly job, one queue message.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
job = log.child(dims={"task_id": "nightly-import"})
|
|
49
|
+
job.info("started", meta={"source": "s3://bucket/feed.csv"})
|
|
50
|
+
job.warning("3 rows skipped")
|
|
51
|
+
job.info("finished", meta={"rows": 10_412})
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
logging.getLogger("importer").info("started", extra={"task_id": "nightly-import"})
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
**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.
|
|
61
|
+
|
|
62
|
+
`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.
|
|
63
|
+
|
|
64
|
+
### Making a task row worth reading
|
|
65
|
+
|
|
66
|
+
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:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# Pass the child logger down. Explicit, and it touches every component signature.
|
|
70
|
+
job = log.child(dims={"task_id": str(work_item_id)})
|
|
71
|
+
upload_availability(communicator, job)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
# Or, through `logging`, per call — no plumbing, one keyword.
|
|
76
|
+
logging.getLogger("SLMWebsiteProcessor").info("Starting work item", extra={"task_id": wid})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Two more things that turn a row from "10 lines" into something you can act on:
|
|
80
|
+
|
|
81
|
+
- **Use the component as the logger name.** `logging.getLogger("SLMWebsiteProcessor")`
|
|
82
|
+
arrives as `meta.logger` and fills the Tasks page's Components column; baked into the
|
|
83
|
+
message string it is only free-text searchable.
|
|
84
|
+
- **Put the outcome in `meta`.** `meta={"result": 0}` on the finish line makes "which jobs
|
|
85
|
+
failed" a query instead of a read. A `print()` is not captured at all — only `logging`
|
|
86
|
+
records and `log.*` calls are.
|
|
87
|
+
|
|
88
|
+
### Saying whether a task failed
|
|
89
|
+
|
|
90
|
+
The Tasks page shows an outcome per job, and the only reliable source for it is the job
|
|
91
|
+
itself. Put it on the finish line:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
job = log.child(dims={"task_id": str(work_item_id)})
|
|
95
|
+
job.info("Starting work item", meta={"param": 3557898})
|
|
96
|
+
...
|
|
97
|
+
job.info(
|
|
98
|
+
f"Finished Task {work_item_id} with result {result}",
|
|
99
|
+
meta={"task": {"ok": result == 0, "result": result, "duration_ms": elapsed_ms}},
|
|
100
|
+
)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
| Field | |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `ok` | `True`/`False`. The one that decides the column. |
|
|
106
|
+
| `result` | Whatever your worker calls it — `0`, `1`, `"skipped"`. Shown next to the outcome. |
|
|
107
|
+
| `status` | A string alternative to `ok`; `ok`/`success`/`succeeded` read as success, anything else as failure. |
|
|
108
|
+
| `duration_ms` | The job's own measure, preferred over the gap between its first and last line. |
|
|
109
|
+
|
|
110
|
+
**Why not just log the failure at `error` level?** Because most workers do not. A line
|
|
111
|
+
reading `Info[SystaskObject] Finished Task 10464854 with result 1` is a failed job logged
|
|
112
|
+
at info, and anything inferring the outcome from log levels calls it a success. LogerHUB
|
|
113
|
+
made that exact substitution once already — the old HTTP success rate used log level and
|
|
114
|
+
counted a 500 logged at info as a win — which is why the page asks the job instead.
|
|
115
|
+
|
|
116
|
+
Without a declared outcome a task reads **errored** if any line was logged at error level,
|
|
117
|
+
and **“said nothing”** otherwise — deliberately not *succeeded*, because a job that never
|
|
118
|
+
reported has only not complained. `ok:false` in the explorer finds exactly the jobs that
|
|
119
|
+
reported failing.
|
|
120
|
+
|
|
121
|
+
### Showing why it failed
|
|
122
|
+
|
|
123
|
+
A row that says "failed" and nothing else sends you to the lines to find out why. Log the
|
|
124
|
+
exception and the reason appears on the row itself:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
try:
|
|
128
|
+
upload_availability(property_id)
|
|
129
|
+
except Exception:
|
|
130
|
+
job.exception("Upload Availability failed") # type, message and stack
|
|
131
|
+
job.info("Finished Task", meta={"task": {"ok": False, "result": 1}})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`log.exception()` and the `logging` handler's `exc_info` both write
|
|
135
|
+
`meta.error = {type, message, stack}`, which the Tasks page reads into its **Why** column:
|
|
136
|
+
`ConnectionResetError: the OTA closed the connection`. The stack stays in the entry for
|
|
137
|
+
when you open it.
|
|
138
|
+
|
|
139
|
+
A logged exception alone marks the task **errored**, not failed — a job can throw, catch,
|
|
140
|
+
retry and finish fine, so only `meta.task.ok` settles it. Both together is the useful
|
|
141
|
+
combination: the outcome says what happened, the exception says why.
|
|
142
|
+
|
|
143
|
+
### A job that finished but runs again
|
|
144
|
+
|
|
145
|
+
A polling worker's job is usually not finished-and-done but finished-and-queued-again. Say
|
|
146
|
+
when, and the Tasks page shows it in a **Next run** column:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
job.info(
|
|
150
|
+
f"Finished Task {wid} with result {result} and reschedule at {next_run}",
|
|
151
|
+
meta={"task": {
|
|
152
|
+
"ok": result == 0,
|
|
153
|
+
"result": result,
|
|
154
|
+
"duration_ms": elapsed_ms,
|
|
155
|
+
"reschedule_at": next_run.isoformat(), # or reschedule_s: 600
|
|
156
|
+
}},
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`reschedule_at` takes an ISO timestamp, epoch milliseconds or epoch seconds.
|
|
161
|
+
`reschedule_s` is the other spelling, for a worker that only knows "in N seconds" — the
|
|
162
|
+
page turns it into a time measured from the line that said it.
|
|
163
|
+
|
|
164
|
+
**It is deliberately not part of the outcome.** This run can have succeeded *and* another
|
|
165
|
+
still be due; folding the two together would lose the only part anyone asks about when a
|
|
166
|
+
queue stops draining. A next-run time already in the past shows amber: it may mean the
|
|
167
|
+
scheduler is behind, or simply that the next run came back under a different `task_id`,
|
|
168
|
+
which the console cannot tell apart.
|
|
169
|
+
|
|
170
|
+
## Levels
|
|
171
|
+
|
|
172
|
+
Python's names and the wire's differ, so both spellings work and map to one wire level:
|
|
173
|
+
|
|
174
|
+
| You write | Arrives as |
|
|
175
|
+
|---|---|
|
|
176
|
+
| `debug` | `debug` |
|
|
177
|
+
| `info` | `info` |
|
|
178
|
+
| `warn`, `warning` | `warn` |
|
|
179
|
+
| `error`, `exception` | `error` |
|
|
180
|
+
| `fatal`, `critical` | `fatal` |
|
|
181
|
+
|
|
182
|
+
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.
|
|
183
|
+
|
|
184
|
+
## Redaction
|
|
185
|
+
|
|
186
|
+
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.
|
|
187
|
+
|
|
188
|
+
- **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.
|
|
189
|
+
- **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.
|
|
190
|
+
|
|
191
|
+
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`.
|
|
192
|
+
|
|
193
|
+
Values over `max_meta_bytes` (8192) are replaced by a marker that still reports the original size.
|
|
194
|
+
|
|
195
|
+
## The spool
|
|
196
|
+
|
|
197
|
+
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.
|
|
198
|
+
|
|
199
|
+
With `spool="/var/lib/app/logerhub"`:
|
|
200
|
+
|
|
201
|
+
- **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.
|
|
202
|
+
- **`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`.
|
|
203
|
+
- A corrupt spool file is moved aside and replaced, reported, not fatal.
|
|
204
|
+
|
|
205
|
+
**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.
|
|
206
|
+
|
|
207
|
+
## Threads, and fork
|
|
208
|
+
|
|
209
|
+
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.
|
|
210
|
+
|
|
211
|
+
**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.
|
|
212
|
+
|
|
213
|
+
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.
|
|
214
|
+
|
|
215
|
+
## TLS
|
|
216
|
+
|
|
217
|
+
Verified by default. For a private CA — `make cert` in the LogerHUB repo produces one:
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
create_logger(…, ca_file="/etc/ssl/certs/internal-ca.pem")
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`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`.
|
|
224
|
+
|
|
225
|
+
## Options
|
|
226
|
+
|
|
227
|
+
| Option | Default | |
|
|
228
|
+
|---|---|---|
|
|
229
|
+
| `url`, `api_key`, `service`, `env` | — | required |
|
|
230
|
+
| `dims` | `{}` | stamped on every entry |
|
|
231
|
+
| `instance` | hostname | the replica identity; `False` omits it |
|
|
232
|
+
| `spool`, `spool_mode` | `None`, `on-failure` | see above |
|
|
233
|
+
| `spool_max_bytes`, `spool_max_age_ms` | 256 MB, 7 days | |
|
|
234
|
+
| `redact_keys` | `()` | extends the defaults |
|
|
235
|
+
| `max_meta_bytes` | 8192 | |
|
|
236
|
+
| `batch_max_entries`, `batch_max_ms`, `batch_max_queue` | 500, 1000, 10000 | |
|
|
237
|
+
| `tls_verify`, `ca_file` | `True`, `None` | |
|
|
238
|
+
| `console` | `False` | echo entries to **stderr** |
|
|
239
|
+
| `on_error` | rate-limited stderr | every internal failure |
|
|
240
|
+
| `register_atexit` | `True` | flush on an orderly exit |
|
|
241
|
+
|
|
242
|
+
`console` writes to stderr, not stdout: a CLI's stdout is its output and a stdio MCP server's is its protocol stream.
|
|
243
|
+
|
|
244
|
+
## Instance identity
|
|
245
|
+
|
|
246
|
+
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.
|
|
247
|
+
|
|
248
|
+
## Not here yet
|
|
249
|
+
|
|
250
|
+
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.
|
|
251
|
+
|
|
252
|
+
## Failure behaviour
|
|
253
|
+
|
|
254
|
+
| What happens | What the client does |
|
|
255
|
+
|---|---|
|
|
256
|
+
| Gateway unreachable | Queues, then spools. Reconnects with jittered backoff to 30s. |
|
|
257
|
+
| Gateway nacks retryably | Returns the batch to the spool and retries. |
|
|
258
|
+
| Gateway nacks terminally | Drops the batch and reports it. Retrying a verdict is an infinite loop. |
|
|
259
|
+
| No ack within 30s | Treats it as a retryable failure. |
|
|
260
|
+
| Queue full, no spool | Drops oldest, counts it, tells the gateway on the next batch. |
|
|
261
|
+
| Anything raises internally | Goes to `on_error`. Never to your call site. |
|
|
262
|
+
|
|
263
|
+
## Development
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
uv venv .venv && VIRTUAL_ENV=.venv uv pip install -e '.[dev]'
|
|
267
|
+
.venv/bin/pytest tests -q
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`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.
|
|
271
|
+
|
|
272
|
+
## Releasing
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
cd packages/python-client
|
|
276
|
+
uv pip install -e '.[publish]'
|
|
277
|
+
|
|
278
|
+
rm -rf dist && uv build # or: python -m build
|
|
279
|
+
twine check dist/* # catches a README PyPI will not render
|
|
280
|
+
twine upload --repository testpypi dist/* # rehearse
|
|
281
|
+
twine upload dist/* # the real thing
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
The username is the literal `__token__` and the password is a PyPI API token, or put them in `~/.pypirc`:
|
|
285
|
+
|
|
286
|
+
```ini
|
|
287
|
+
[pypi]
|
|
288
|
+
username = __token__
|
|
289
|
+
password = pypi-...
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Two things that make this a one-way door:
|
|
293
|
+
|
|
294
|
+
- **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.
|
|
295
|
+
- **The name is claimed on first publish** and a project cannot be renamed.
|
|
296
|
+
|
|
297
|
+
On TestPyPI, install with `--extra-index-url https://pypi.org/simple/` as well — `websocket-client` is not mirrored there.
|
|
298
|
+
|
|
299
|
+
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.
|