logerhub-client 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Stream structured logs to a LogerHUB gateway.
2
+
3
+ from logerhub import create_logger
4
+
5
+ log = create_logger(url="wss://logs.example.com/v1/stream", api_key="lgb_live_…",
6
+ service="billing", env="prod")
7
+ log.info("charge captured", dims={"company_id": "acme"}, meta={"amount_cents": 1200})
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from .console import print_line
13
+ from .handler import LogerHubHandler
14
+ from .logger import Logger, create_logger
15
+ from .protocol import KINDS, LEVELS, wire_level
16
+
17
+ __all__ = [
18
+ "KINDS",
19
+ "LEVELS",
20
+ "LogerHubHandler",
21
+ "Logger",
22
+ "create_logger",
23
+ "print_line",
24
+ "wire_level",
25
+ ]
26
+ __version__ = "0.1.0"
logerhub/batcher.py ADDED
@@ -0,0 +1,133 @@
1
+ """The in-memory queue, and cutting it into batches.
2
+
3
+ Mirrors `packages/client/src/batcher.ts`. Two properties carry the design:
4
+
5
+ Entries are dropped **oldest first** when the queue is full. Under sustained pressure the
6
+ newest lines are the ones describing what is happening now, and the older ones have
7
+ usually already been superseded.
8
+
9
+ A drop is always **counted and reported**. `droppedSinceLast` rides the next batch frame
10
+ and the gateway records it, so a loss is visible in the console rather than being a gap
11
+ nobody can distinguish from quiet. Dropping is allowed; dropping silently is not.
12
+
13
+ Unlike the TypeScript version there is no timer thread here. `max_ms` is enforced by the
14
+ sender thread's own loop, which waits on an event with a timeout — one thread is the whole
15
+ budget for a logging library.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import threading
22
+ import uuid
23
+ from typing import Any, Callable
24
+
25
+ from .protocol import batch_frame
26
+
27
+ DEFAULT_MAX_ENTRIES = 500
28
+ DEFAULT_MAX_MS = 1000
29
+ DEFAULT_MAX_QUEUE = 10_000
30
+
31
+
32
+ def _sane(value: Any, fallback: int, minimum: int = 1) -> int:
33
+ """A finite int at or above `minimum`, else the fallback.
34
+
35
+ Used on both constructor arguments and on the gateway's advertised limits, because
36
+ neither is more trustworthy than the other: one is a caller's typo and the other is a
37
+ frame off a socket.
38
+ """
39
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
40
+ return fallback
41
+ if isinstance(value, float) and not math.isfinite(value):
42
+ return fallback
43
+ value = int(value)
44
+ return value if value >= minimum else fallback
45
+
46
+
47
+ class Batcher:
48
+ def __init__(
49
+ self,
50
+ *,
51
+ max_entries: int = DEFAULT_MAX_ENTRIES,
52
+ max_ms: int = DEFAULT_MAX_MS,
53
+ max_queue: int = DEFAULT_MAX_QUEUE,
54
+ on_cut: Callable[[], None] | None = None,
55
+ ) -> None:
56
+ self._configured_cut = _sane(max_entries, DEFAULT_MAX_ENTRIES)
57
+ self._cut_size = self._configured_cut
58
+ self.max_ms = _sane(max_ms, DEFAULT_MAX_MS)
59
+ self._max_queue = _sane(max_queue, DEFAULT_MAX_QUEUE)
60
+ self._on_cut = on_cut
61
+ self._queue: list[dict[str, Any]] = []
62
+ self._dropped = 0
63
+ self._lock = threading.Lock()
64
+
65
+ def add(self, entry: dict[str, Any]) -> None:
66
+ """Queue an entry, dropping the oldest if the queue is full."""
67
+ with self._lock:
68
+ self._queue.append(entry)
69
+ overflow = len(self._queue) - self._max_queue
70
+ if overflow > 0:
71
+ del self._queue[:overflow]
72
+ self._dropped += overflow
73
+ ready = len(self._queue) >= self._cut_size
74
+ # Outside the lock: a callback that blocks or throws must not hold the queue, and
75
+ # the sender it wakes will take the lock itself.
76
+ if ready and self._on_cut is not None:
77
+ try:
78
+ self._on_cut()
79
+ except Exception:
80
+ # Costs a wakeup; `max_ms` still gets the batch out.
81
+ pass
82
+
83
+ def cut(self) -> dict[str, Any] | None:
84
+ """The next batch frame, or None when the queue is empty."""
85
+ with self._lock:
86
+ if not self._queue:
87
+ return None
88
+ entries = self._queue[: self._cut_size]
89
+ del self._queue[: self._cut_size]
90
+ dropped, self._dropped = self._dropped, 0
91
+ return batch_frame(uuid.uuid4().hex, entries, dropped=dropped)
92
+
93
+ def set_limits(self, max_entries_per_batch: Any) -> None:
94
+ """Adopt the gateway's advertised batch size, if it is smaller than ours.
95
+
96
+ Only downwards. The gateway's `hello` says what it will accept; it is not a licence
97
+ to send bigger batches than this process was configured to send.
98
+ """
99
+ advertised = _sane(max_entries_per_batch, self._configured_cut)
100
+ with self._lock:
101
+ self._cut_size = min(self._configured_cut, advertised)
102
+
103
+ def pending(self) -> int:
104
+ with self._lock:
105
+ return len(self._queue)
106
+
107
+ def dropped_since_last(self) -> int:
108
+ """Drops not yet reported on a batch. Reading does not consume the count.
109
+
110
+ Non-destructive on purpose: the count is consumed by `cut`, when a batch actually
111
+ leaves. A reader that cleared it would make the loss invisible if no batch
112
+ followed — and a queue that is overflowing is exactly the case where none may.
113
+ """
114
+ with self._lock:
115
+ return self._dropped
116
+
117
+ def drain(self) -> list[dict[str, Any]]:
118
+ """Every remaining batch, for a final flush at shutdown."""
119
+ out: list[dict[str, Any]] = []
120
+ while (frame := self.cut()) is not None:
121
+ out.append(frame)
122
+ return out
123
+
124
+ def clear(self) -> None:
125
+ """Forget everything queued, without counting it as a drop.
126
+
127
+ For the child of a `fork`: those entries belong to the parent, which still holds
128
+ them and will send them. Counting them here would report a loss that did not
129
+ happen, in the one place a wrong count is worse than no count.
130
+ """
131
+ with self._lock:
132
+ self._queue.clear()
133
+ self._dropped = 0
logerhub/console.py ADDED
@@ -0,0 +1,45 @@
1
+ """Printing an entry locally, for development.
2
+
3
+ Writes to **stderr**, not stdout: a CLI's stdout is its output and a stdio MCP server's is
4
+ its protocol stream, and a log line written there corrupts both. No in-flight block and no
5
+ colour negotiation — the TypeScript client earns those by owning the terminal, and this is
6
+ a library that is a guest in someone else's process.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from typing import Any, Mapping
13
+
14
+ LEVEL_WIDTH = 5
15
+
16
+ #: Dropped from the printed line: the hostname is the same on every line of a local run,
17
+ #: so it is noise on a developer's screen while still being essential in the gateway.
18
+ LOCAL_NOISE = frozenset({"instance"})
19
+
20
+
21
+ def format_entry(entry: Mapping[str, Any]) -> str:
22
+ level = str(entry.get("level", "info")).upper().ljust(LEVEL_WIDTH)
23
+ parts = [str(entry.get("ts", "")), level, str(entry.get("msg", ""))]
24
+ dims = entry.get("dims")
25
+ if isinstance(dims, dict):
26
+ tail = " ".join(f"{k}={v}" for k, v in dims.items() if k not in LOCAL_NOISE)
27
+ if tail:
28
+ parts.append(tail)
29
+ return " ".join(p for p in parts if p)
30
+
31
+
32
+ def print_entry(entry: Mapping[str, Any]) -> None:
33
+ try:
34
+ sys.stderr.write(format_entry(entry) + "\n")
35
+ except Exception:
36
+ # A terminal that will not take the line must not cost the entry.
37
+ pass
38
+
39
+
40
+ def print_line(text: str) -> None:
41
+ """Write a line locally and send nothing. For banners and startup notices."""
42
+ try:
43
+ sys.stderr.write(text + "\n")
44
+ except Exception:
45
+ pass
logerhub/handler.py ADDED
@@ -0,0 +1,126 @@
1
+ """A `logging.Handler`, so an existing codebase ships without being rewritten.
2
+
3
+ log = create_logger(url=…, api_key=…, service="billing", env="prod")
4
+ logging.getLogger().addHandler(LogerHubHandler(log))
5
+
6
+ Every `logger.info(...)` already in the codebase then streams, with its logger name,
7
+ exception and any `dims`/`meta` passed through `extra`.
8
+
9
+ The one rule this module cannot break: **never emit through `logging`**. A handler on the
10
+ root logger that logs its own failures is an unbounded recursion, so failures go to the
11
+ logger's `on_error` — which writes to stderr — and `handleError` is overridden to stop the
12
+ default implementation printing to stderr on every record.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import bisect
18
+ import logging
19
+ import traceback
20
+ from typing import Any, Mapping
21
+
22
+ from .logger import Logger
23
+
24
+ #: Python level numbers and the wire level each one means, in ascending order.
25
+ #:
26
+ #: Searched with bisect so a level *between* the standard ones rounds **down** to the
27
+ #: nearest named one: 25 (common for a custom "NOTICE") is an `info`, not a `warn`.
28
+ #: Rounding up would invent severity, and a log line that claims to be a warning when the
29
+ #: application said otherwise is worse than one that under-reports.
30
+ _LEVEL_POINTS: tuple[tuple[int, str], ...] = (
31
+ (logging.NOTSET, "debug"),
32
+ (logging.DEBUG, "debug"),
33
+ (logging.INFO, "info"),
34
+ (logging.WARNING, "warn"),
35
+ (logging.ERROR, "error"),
36
+ (logging.CRITICAL, "fatal"),
37
+ )
38
+ _LEVEL_NUMBERS = [number for number, _ in _LEVEL_POINTS]
39
+
40
+ #: The only `extra` keys read. Anything else is ignored rather than folded into `meta`:
41
+ #: `extra` is a namespace the application owns, and hoovering it up would ship whatever a
42
+ #: library happened to attach, including things nobody meant to send.
43
+ RECOGNISED_EXTRA = ("dims", "meta", "task_id", "trace_id")
44
+
45
+
46
+ def wire_level_for(levelno: int) -> str:
47
+ """The wire level for a `logging` level number, rounding down between the named ones."""
48
+ index = bisect.bisect_right(_LEVEL_NUMBERS, levelno) - 1
49
+ return _LEVEL_POINTS[max(0, index)][1]
50
+
51
+
52
+ class LogerHubHandler(logging.Handler):
53
+ """Streams `logging` records through a LogerHUB logger."""
54
+
55
+ def __init__(self, logger: Logger, level: int = logging.NOTSET) -> None:
56
+ super().__init__(level=level)
57
+ self._logger = logger
58
+
59
+ def emit(self, record: logging.LogRecord) -> None:
60
+ try:
61
+ dims, meta = self._extract(record)
62
+ self._logger.log(
63
+ wire_level_for(record.levelno),
64
+ # The interpolated message, not a Formatter's output: a formatter prefixes
65
+ # the level and timestamp, which the entry already carries as fields, so
66
+ # shipping both would duplicate them in the line a human reads.
67
+ record.getMessage(),
68
+ dims=dims or None,
69
+ meta=meta or None,
70
+ )
71
+ except Exception:
72
+ self.handleError(record)
73
+
74
+ def handleError(self, record: logging.LogRecord) -> None:
75
+ """Swallow. The default prints a traceback to stderr for every failed record.
76
+
77
+ Overridden rather than left alone because the failure modes here are systemic, not
78
+ per-record — an unreachable gateway, a full queue — so the default turns one
79
+ problem into a line of noise per log call. The logger's own `on_error` already
80
+ reports it, once, rate-limited.
81
+ """
82
+ return
83
+
84
+ # -- reading the record ----------------------------------------------------
85
+
86
+ def _extract(self, record: logging.LogRecord) -> tuple[dict[str, str], dict[str, Any]]:
87
+ dims: dict[str, str] = {}
88
+ meta: dict[str, Any] = {}
89
+
90
+ raw_dims = getattr(record, "dims", None)
91
+ if isinstance(raw_dims, Mapping):
92
+ dims.update({str(k): str(v) for k, v in raw_dims.items() if v is not None})
93
+ # `task_id` and `trace_id` are accepted at the top of `extra` as well as inside
94
+ # `dims`, because `extra={"task_id": job.id}` is what anyone writes first and
95
+ # being pedantic about it would cost the grouping the field exists for.
96
+ for key in ("task_id", "trace_id"):
97
+ value = getattr(record, key, None)
98
+ if value is not None and key not in dims:
99
+ dims[key] = str(value)
100
+
101
+ raw_meta = getattr(record, "meta", None)
102
+ if isinstance(raw_meta, Mapping):
103
+ meta.update(dict(raw_meta))
104
+
105
+ # The logger's own name: `billing.invoices` is how a Python codebase says which
106
+ # part spoke, and losing it would make every line look like it came from one place.
107
+ if record.name and record.name != "root":
108
+ meta.setdefault("logger", record.name)
109
+
110
+ if record.exc_info and record.exc_info[1] is not None:
111
+ exc = record.exc_info[1]
112
+ meta.setdefault(
113
+ "error",
114
+ {
115
+ "type": type(exc).__name__,
116
+ "message": str(exc),
117
+ "stack": "".join(traceback.format_exception(*record.exc_info)),
118
+ },
119
+ )
120
+ elif record.exc_text:
121
+ meta.setdefault("error", {"stack": record.exc_text})
122
+
123
+ if record.stack_info:
124
+ meta.setdefault("stack", record.stack_info)
125
+
126
+ return dims, meta