lauren-logging 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.
- lauren_logging-0.1.0/PKG-INFO +69 -0
- lauren_logging-0.1.0/README.md +60 -0
- lauren_logging-0.1.0/pyproject.toml +18 -0
- lauren_logging-0.1.0/setup.cfg +4 -0
- lauren_logging-0.1.0/src/lauren_logging/__init__.py +354 -0
- lauren_logging-0.1.0/src/lauren_logging/cli.py +38 -0
- lauren_logging-0.1.0/src/lauren_logging.egg-info/PKG-INFO +69 -0
- lauren_logging-0.1.0/src/lauren_logging.egg-info/SOURCES.txt +9 -0
- lauren_logging-0.1.0/src/lauren_logging.egg-info/dependency_links.txt +1 -0
- lauren_logging-0.1.0/src/lauren_logging.egg-info/entry_points.txt +2 -0
- lauren_logging-0.1.0/src/lauren_logging.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lauren-logging
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Structured-logging library, a drop-in upgrade from stdlib logging — JSON/pretty records, request-scoped context, file and HTTP sinks.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# lauren-logging
|
|
11
|
+
|
|
12
|
+
`lauren-logging` is a structured-logging library for Python that aims to be a
|
|
13
|
+
drop-in upgrade from the stdlib `logging` module without a heavy rewrite. It emits
|
|
14
|
+
JSON (or pretty console) records with stable field names, request-scoped context
|
|
15
|
+
(auto-injected trace_id / user_id / request_id), and sinks for stdout, files with
|
|
16
|
+
rotation, and HTTP/Loki collectors. It is for services that want machine-readable
|
|
17
|
+
logs in production but readable logs in development — and that want both from the
|
|
18
|
+
same call sites.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- `get_logger(name)` returns a logger whose `.info/.error(...)` accept a free-form
|
|
23
|
+
message plus keyword fields, all serialized as structured records.
|
|
24
|
+
- Request-scoped context via `bind(**fields)` / `with_context(...)`; child loggers
|
|
25
|
+
inherit bound fields automatically, so trace_id need not be threaded by hand.
|
|
26
|
+
- Handlers for stdout (JSON or pretty, picked by `LAUREN_PRETTY`), rotating files,
|
|
27
|
+
and an HTTP sink (Loki/Batch-format) for central collection.
|
|
28
|
+
- Sampling and redaction rules (regex-based PII masking) configured once per app.
|
|
29
|
+
- Stdlib interop: a `LaurenHandler` bridges third-party `logging` calls into
|
|
30
|
+
structured records so libraries that use stdlib still emit JSON.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install lauren-logging # core: stdout + file sinks
|
|
36
|
+
pip install "lauren-logging[loki]" # adds the HTTP/Loki sink + httpx
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from lauren_logging import get_logger, with_context
|
|
43
|
+
|
|
44
|
+
log = get_logger("billing")
|
|
45
|
+
|
|
46
|
+
with with_context(trace_id="abc123", user_id="u_42"):
|
|
47
|
+
log.info("invoice created", invoice_id="inv_9001", amount_cents=4200)
|
|
48
|
+
try:
|
|
49
|
+
1 / 0
|
|
50
|
+
except ZeroDivisionError:
|
|
51
|
+
log.error("division failed", exc_info=True)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## API
|
|
55
|
+
|
|
56
|
+
- `get_logger(name) -> Logger` — main entry; `.info/.warning/.error(msg, **fields)`.
|
|
57
|
+
- `with_context(**fields)` — context manager pushing fields onto the current scope.
|
|
58
|
+
- `Logger.bind(**fields) -> Logger` — child logger with permanent fields.
|
|
59
|
+
- `add_handler(handler)` — `StreamHandler`, `RotatingFileHandler`, `HttpSink`.
|
|
60
|
+
|
|
61
|
+
## Configuration
|
|
62
|
+
|
|
63
|
+
`LAUREN_LEVEL` (default `INFO`), `LAUREN_PRETTY` (truthy → color console),
|
|
64
|
+
`LAUREN_JSON` (force JSON), and `LAUREN_SINK` (`stdout|file|loki`) are honored out of
|
|
65
|
+
the box; a `lauren-logging.toml` provides per-logger redaction and sampling rules.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# lauren-logging
|
|
2
|
+
|
|
3
|
+
`lauren-logging` is a structured-logging library for Python that aims to be a
|
|
4
|
+
drop-in upgrade from the stdlib `logging` module without a heavy rewrite. It emits
|
|
5
|
+
JSON (or pretty console) records with stable field names, request-scoped context
|
|
6
|
+
(auto-injected trace_id / user_id / request_id), and sinks for stdout, files with
|
|
7
|
+
rotation, and HTTP/Loki collectors. It is for services that want machine-readable
|
|
8
|
+
logs in production but readable logs in development — and that want both from the
|
|
9
|
+
same call sites.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- `get_logger(name)` returns a logger whose `.info/.error(...)` accept a free-form
|
|
14
|
+
message plus keyword fields, all serialized as structured records.
|
|
15
|
+
- Request-scoped context via `bind(**fields)` / `with_context(...)`; child loggers
|
|
16
|
+
inherit bound fields automatically, so trace_id need not be threaded by hand.
|
|
17
|
+
- Handlers for stdout (JSON or pretty, picked by `LAUREN_PRETTY`), rotating files,
|
|
18
|
+
and an HTTP sink (Loki/Batch-format) for central collection.
|
|
19
|
+
- Sampling and redaction rules (regex-based PII masking) configured once per app.
|
|
20
|
+
- Stdlib interop: a `LaurenHandler` bridges third-party `logging` calls into
|
|
21
|
+
structured records so libraries that use stdlib still emit JSON.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install lauren-logging # core: stdout + file sinks
|
|
27
|
+
pip install "lauren-logging[loki]" # adds the HTTP/Loki sink + httpx
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from lauren_logging import get_logger, with_context
|
|
34
|
+
|
|
35
|
+
log = get_logger("billing")
|
|
36
|
+
|
|
37
|
+
with with_context(trace_id="abc123", user_id="u_42"):
|
|
38
|
+
log.info("invoice created", invoice_id="inv_9001", amount_cents=4200)
|
|
39
|
+
try:
|
|
40
|
+
1 / 0
|
|
41
|
+
except ZeroDivisionError:
|
|
42
|
+
log.error("division failed", exc_info=True)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
- `get_logger(name) -> Logger` — main entry; `.info/.warning/.error(msg, **fields)`.
|
|
48
|
+
- `with_context(**fields)` — context manager pushing fields onto the current scope.
|
|
49
|
+
- `Logger.bind(**fields) -> Logger` — child logger with permanent fields.
|
|
50
|
+
- `add_handler(handler)` — `StreamHandler`, `RotatingFileHandler`, `HttpSink`.
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
`LAUREN_LEVEL` (default `INFO`), `LAUREN_PRETTY` (truthy → color console),
|
|
55
|
+
`LAUREN_JSON` (force JSON), and `LAUREN_SINK` (`stdout|file|loki`) are honored out of
|
|
56
|
+
the box; a `lauren-logging.toml` provides per-logger redaction and sampling rules.
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "lauren-logging"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Structured-logging library, a drop-in upgrade from stdlib logging — JSON/pretty records, request-scoped context, file and HTTP sinks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = ""}]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
lauren-logging = "lauren_logging.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""lauren-logging — structured-logging library, a drop-in upgrade from stdlib ``logging``.
|
|
2
|
+
|
|
3
|
+
Emits JSON (or pretty console) records with stable field names, request-scoped
|
|
4
|
+
context (auto-injected trace_id / user_id / request_id), and sinks for stdout,
|
|
5
|
+
files with rotation, and HTTP/Loki collectors.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Any, Callable, Iterable, Mapping
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"get_logger",
|
|
24
|
+
"with_context",
|
|
25
|
+
"Logger",
|
|
26
|
+
"add_handler",
|
|
27
|
+
"StreamHandler",
|
|
28
|
+
"RotatingFileHandler",
|
|
29
|
+
"HttpSink",
|
|
30
|
+
"LaurenHandler",
|
|
31
|
+
"RedactionRule",
|
|
32
|
+
"LaurenError",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LaurenError(Exception):
|
|
37
|
+
"""Raised when a lauren-logging sink or redaction rule is misconfigured."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_LEVELS = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40, "CRITICAL": 50}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _level_from_env(default: str = "INFO") -> int:
|
|
44
|
+
return _LEVELS.get(os.environ.get("LAUREN_LEVEL", default).upper(), _LEVELS[default])
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# -- context scope -----------------------------------------------------
|
|
48
|
+
@dataclass
|
|
49
|
+
class _Scope:
|
|
50
|
+
fields: dict[str, Any] = field(default_factory=dict)
|
|
51
|
+
|
|
52
|
+
def child(self, **fields: Any) -> "_Scope":
|
|
53
|
+
merged = dict(self.fields)
|
|
54
|
+
merged.update(fields)
|
|
55
|
+
return _Scope(fields=merged)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_CONTEXT_STACK: list[_Scope] = [_Scope()]
|
|
59
|
+
_CONTEXT_LOCK = threading.Lock()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _current_scope() -> _Scope:
|
|
63
|
+
return _CONTEXT_STACK[-1]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def with_context(**fields: Any):
|
|
67
|
+
"""Context manager pushing ``fields`` onto the current scope.
|
|
68
|
+
|
|
69
|
+
Child loggers and bound loggers inherit bound fields automatically.
|
|
70
|
+
"""
|
|
71
|
+
return _ContextManager(**fields)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _ContextManager:
|
|
75
|
+
"""Context manager pushing fields onto the request scope."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, **fields: Any) -> None:
|
|
78
|
+
self._fields = fields
|
|
79
|
+
self._scope: _Scope | None = None
|
|
80
|
+
|
|
81
|
+
def __enter__(self) -> "_ContextManager":
|
|
82
|
+
with _CONTEXT_LOCK:
|
|
83
|
+
self._scope = _current_scope().child(**self._fields)
|
|
84
|
+
_CONTEXT_STACK.append(self._scope)
|
|
85
|
+
return self
|
|
86
|
+
|
|
87
|
+
def __exit__(self, *exc: Any) -> None:
|
|
88
|
+
with _CONTEXT_LOCK:
|
|
89
|
+
if _CONTEXT_STACK[-1] is self._scope:
|
|
90
|
+
_CONTEXT_STACK.pop()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# -- handlers / sinks --------------------------------------------------
|
|
94
|
+
class StreamHandler:
|
|
95
|
+
"""Write structured records to a stream (stdout by default)."""
|
|
96
|
+
|
|
97
|
+
def __init__(self, stream: Any | None = None, *, pretty: bool | None = None) -> None:
|
|
98
|
+
self.stream = stream or sys.stdout
|
|
99
|
+
if pretty is None:
|
|
100
|
+
pretty = _truthy(os.environ.get("LAUREN_PRETTY"))
|
|
101
|
+
self.pretty = pretty
|
|
102
|
+
self._lock = threading.Lock()
|
|
103
|
+
|
|
104
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
105
|
+
"""Serialize and write ``record`` to the stream."""
|
|
106
|
+
text = _format(record, pretty=self.pretty)
|
|
107
|
+
with self._lock:
|
|
108
|
+
self.stream.write(text + "\n")
|
|
109
|
+
self.stream.flush()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class RotatingFileHandler:
|
|
113
|
+
"""Rotating-file sink that rolls over at ``max_bytes`` keeping ``backup_count`` archives."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, path: str, *, max_bytes: int = 1_000_000, backup_count: int = 3) -> None:
|
|
116
|
+
self.path = path
|
|
117
|
+
self.max_bytes = max_bytes
|
|
118
|
+
self.backup_count = backup_count
|
|
119
|
+
self._lock = threading.Lock()
|
|
120
|
+
self._ensure_file()
|
|
121
|
+
|
|
122
|
+
def _ensure_file(self) -> None:
|
|
123
|
+
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
|
|
124
|
+
if not os.path.exists(self.path):
|
|
125
|
+
open(self.path, "a").close()
|
|
126
|
+
|
|
127
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
128
|
+
text = _format(record, pretty=False)
|
|
129
|
+
with self._lock:
|
|
130
|
+
if os.path.exists(self.path) and os.path.getsize(self.path) >= self.max_bytes:
|
|
131
|
+
self._rotate()
|
|
132
|
+
with open(self.path, "a", encoding="utf-8") as fh:
|
|
133
|
+
fh.write(text + "\n")
|
|
134
|
+
|
|
135
|
+
def _rotate(self) -> None:
|
|
136
|
+
for i in range(self.backup_count - 1, 0, -1):
|
|
137
|
+
src = f"{self.path}.{i}"
|
|
138
|
+
dst = f"{self.path}.{i + 1}"
|
|
139
|
+
if os.path.exists(src):
|
|
140
|
+
os.replace(src, dst)
|
|
141
|
+
os.replace(self.path, f"{self.path}.1")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class HttpSink:
|
|
145
|
+
"""HTTP/Loki sink; POSTs batches of records to ``endpoint``.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
endpoint: URL to POST records to.
|
|
149
|
+
batch_size: Flush after this many records.
|
|
150
|
+
transport: Optional callable ``(endpoint, body) -> None`` used by
|
|
151
|
+
tests to avoid the network.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
endpoint: str,
|
|
157
|
+
*,
|
|
158
|
+
batch_size: int = 50,
|
|
159
|
+
transport: Callable[[str, list[dict[str, Any]]], None] | None = None,
|
|
160
|
+
) -> None:
|
|
161
|
+
self.endpoint = endpoint
|
|
162
|
+
self.batch_size = batch_size
|
|
163
|
+
self._buffer: list[dict[str, Any]] = []
|
|
164
|
+
self._lock = threading.Lock()
|
|
165
|
+
self._transport = transport
|
|
166
|
+
|
|
167
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
168
|
+
flush = False
|
|
169
|
+
with self._lock:
|
|
170
|
+
self._buffer.append(record)
|
|
171
|
+
if len(self._buffer) >= self.batch_size:
|
|
172
|
+
flush = True
|
|
173
|
+
if flush:
|
|
174
|
+
self.flush()
|
|
175
|
+
|
|
176
|
+
def flush(self) -> None:
|
|
177
|
+
"""Send the buffered batch to the endpoint."""
|
|
178
|
+
with self._lock:
|
|
179
|
+
batch, self._buffer = self._buffer, []
|
|
180
|
+
if not batch:
|
|
181
|
+
return
|
|
182
|
+
if self._transport is None:
|
|
183
|
+
_http_post_json(self.endpoint, batch) # pragma: no cover - network
|
|
184
|
+
else:
|
|
185
|
+
self._transport(self.endpoint, batch)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _http_post_json(endpoint: str, body: Any) -> None:
|
|
189
|
+
import urllib.request
|
|
190
|
+
|
|
191
|
+
data = json.dumps(body).encode("utf-8")
|
|
192
|
+
req = urllib.request.Request(endpoint, data=data, headers={"Content-Type": "application/json"}, method="POST")
|
|
193
|
+
urllib.request.urlopen(req, timeout=5).read() # pragma: no cover - network
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class LaurenHandler(logging.Handler):
|
|
197
|
+
"""Bridge stdlib ``logging`` calls into structured records.
|
|
198
|
+
|
|
199
|
+
Attach with ``logging.getLogger(...).addHandler(LaurenHandler(target_logger))``.
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
def __init__(self, target: "Logger") -> None:
|
|
203
|
+
super().__init__()
|
|
204
|
+
self.target = target
|
|
205
|
+
|
|
206
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
207
|
+
"""Convert a stdlib log record into a structured record and emit it."""
|
|
208
|
+
try:
|
|
209
|
+
message = record.getMessage()
|
|
210
|
+
level = record.levelname.lower() if hasattr(record, "levelname") else "info"
|
|
211
|
+
fields = {k: v for k, v in record.__dict__.items()
|
|
212
|
+
if k not in {"msg", "args", "levelname", "levelno", "name", "message",
|
|
213
|
+
"pathname", "filename", "module", "exc_info", "exc_text",
|
|
214
|
+
"stack_info", "lineno", "funcName", "created", "msecs",
|
|
215
|
+
"relativeCreated", "thread", "threadName",
|
|
216
|
+
"processName", "process", "taskName"}}
|
|
217
|
+
self.target._log(level, message, fields)
|
|
218
|
+
except Exception:
|
|
219
|
+
self.handleError(record)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# -- redaction ---------------------------------------------------------
|
|
223
|
+
@dataclass
|
|
224
|
+
class RedactionRule:
|
|
225
|
+
"""Regex-based PII redaction rule.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
fields: Field names to redact.
|
|
229
|
+
pattern: Optional regex to redact within field values.
|
|
230
|
+
replacement: Replacement text.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
fields: set[str] = field(default_factory=set)
|
|
234
|
+
pattern: str | None = None
|
|
235
|
+
replacement: str = "***REDACTED***"
|
|
236
|
+
|
|
237
|
+
def apply(self, fields: dict[str, Any]) -> dict[str, Any]:
|
|
238
|
+
out = dict(fields)
|
|
239
|
+
for k in list(out.keys()):
|
|
240
|
+
if k in self.fields:
|
|
241
|
+
out[k] = self.replacement
|
|
242
|
+
elif self.pattern is not None:
|
|
243
|
+
import re
|
|
244
|
+
|
|
245
|
+
out[k] = re.sub(self.pattern, self.replacement, str(out[k]))
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
# -- logger ------------------------------------------------------------
|
|
250
|
+
class Logger:
|
|
251
|
+
"""A structured logger.
|
|
252
|
+
|
|
253
|
+
Use :func:`get_logger` to obtain an instance; call ``.info/.warning/.error``
|
|
254
|
+
with a free-form message plus keyword fields.
|
|
255
|
+
"""
|
|
256
|
+
|
|
257
|
+
def __init__(
|
|
258
|
+
self,
|
|
259
|
+
name: str,
|
|
260
|
+
*,
|
|
261
|
+
level: int | None = None,
|
|
262
|
+
handlers: Iterable[Any] | None = None,
|
|
263
|
+
scope: _Scope | None = None,
|
|
264
|
+
redactions: Iterable[RedactionRule] | None = None,
|
|
265
|
+
sample_rate: float = 1.0,
|
|
266
|
+
) -> None:
|
|
267
|
+
self.name = name
|
|
268
|
+
self.level = level if level is not None else _level_from_env()
|
|
269
|
+
self.handlers: list[Any] = list(handlers or [])
|
|
270
|
+
self._scope = scope or _Scope()
|
|
271
|
+
self.redactions = list(redactions or [])
|
|
272
|
+
self.sample_rate = sample_rate
|
|
273
|
+
if not self.handlers:
|
|
274
|
+
self.handlers = [StreamHandler()]
|
|
275
|
+
|
|
276
|
+
def bind(self, **fields: Any) -> "Logger":
|
|
277
|
+
"""Return a child logger with permanent bound fields."""
|
|
278
|
+
return Logger(
|
|
279
|
+
name=self.name,
|
|
280
|
+
level=self.level,
|
|
281
|
+
handlers=self.handlers,
|
|
282
|
+
scope=self._scope.child(**fields),
|
|
283
|
+
redactions=self.redactions,
|
|
284
|
+
sample_rate=self.sample_rate,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def info(self, msg: str, **fields: Any) -> None:
|
|
288
|
+
"""Log at INFO level."""
|
|
289
|
+
self._log("info", msg, fields)
|
|
290
|
+
|
|
291
|
+
def warning(self, msg: str, **fields: Any) -> None:
|
|
292
|
+
"""Log at WARNING level."""
|
|
293
|
+
self._log("warning", msg, fields)
|
|
294
|
+
|
|
295
|
+
def error(self, msg: str, **fields: Any) -> None:
|
|
296
|
+
"""Log at ERROR level; pass ``exc_info=True`` to attach a traceback."""
|
|
297
|
+
exc = fields.pop("exc_info", False)
|
|
298
|
+
if exc:
|
|
299
|
+
import traceback
|
|
300
|
+
|
|
301
|
+
fields["traceback"] = traceback.format_exc()
|
|
302
|
+
self._log("error", msg, fields)
|
|
303
|
+
|
|
304
|
+
def debug(self, msg: str, **fields: Any) -> None:
|
|
305
|
+
"""Log at DEBUG level."""
|
|
306
|
+
self._log("debug", msg, fields)
|
|
307
|
+
|
|
308
|
+
def _log(self, level: str, msg: str, fields: dict[str, Any]) -> None:
|
|
309
|
+
levelno = _LEVELS.get(level.upper(), 20)
|
|
310
|
+
if levelno < self.level:
|
|
311
|
+
return
|
|
312
|
+
merged = dict(self._scope.fields)
|
|
313
|
+
merged.update(_current_scope().fields)
|
|
314
|
+
merged.update(fields)
|
|
315
|
+
for rule in self.redactions:
|
|
316
|
+
merged = rule.apply(merged)
|
|
317
|
+
record = {
|
|
318
|
+
"ts": time.time(),
|
|
319
|
+
"level": level,
|
|
320
|
+
"logger": self.name,
|
|
321
|
+
"message": msg,
|
|
322
|
+
**merged,
|
|
323
|
+
}
|
|
324
|
+
for h in self.handlers:
|
|
325
|
+
h.emit(record)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def get_logger(name: str, **kwargs: Any) -> Logger:
|
|
329
|
+
"""Return a :class:`Logger` named ``name``.
|
|
330
|
+
|
|
331
|
+
Extra keyword arguments are forwarded to the :class:`Logger` constructor.
|
|
332
|
+
"""
|
|
333
|
+
return Logger(name, **kwargs)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def add_handler(handler: Any, *, logger_name: str | None = None) -> None:
|
|
337
|
+
"""Attach ``handler`` to the named logger (default: the root logger)."""
|
|
338
|
+
name = logger_name or "root"
|
|
339
|
+
logger = get_logger(name)
|
|
340
|
+
logger.handlers.append(handler)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _format(record: dict[str, Any], *, pretty: bool) -> str:
|
|
344
|
+
if pretty:
|
|
345
|
+
level = record.get("level", "info").upper()
|
|
346
|
+
msg = record.get("message", "")
|
|
347
|
+
ctx = " ".join(f"{k}={v}" for k, v in record.items()
|
|
348
|
+
if k not in {"ts", "level", "logger", "message"})
|
|
349
|
+
return f"{level} {record.get('logger', '')} {msg} {ctx}".rstrip()
|
|
350
|
+
return json.dumps(record, sort_keys=True, default=str)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _truthy(value: str | None) -> bool:
|
|
354
|
+
return value is not None and value.lower() in {"1", "true", "yes", "on"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""CLI entry for lauren-logging.
|
|
2
|
+
|
|
3
|
+
The README documents no CLI surface; this command emits a single structured
|
|
4
|
+
record per level so teams can verify sink configuration end-to-end.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from . import StreamHandler, __version__, get_logger
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(prog="lauren-logging", description="Structured-logging diagnostics.")
|
|
17
|
+
parser.add_argument("--version", action="version", version=f"lauren-logging {__version__}")
|
|
18
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
19
|
+
ping = sub.add_parser("ping", help="emit one record per log level")
|
|
20
|
+
ping.add_argument("--name", default="lauren-logging")
|
|
21
|
+
return parser
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main(argv: list[str] | None = None) -> int:
|
|
25
|
+
"""Entry point for the ``lauren-logging`` console script."""
|
|
26
|
+
args = _build_parser().parse_args(argv)
|
|
27
|
+
if args.command == "ping":
|
|
28
|
+
log = get_logger(args.name)
|
|
29
|
+
log.debug("debug message", source="cli")
|
|
30
|
+
log.info("info message", source="cli")
|
|
31
|
+
log.warning("warning message", source="cli")
|
|
32
|
+
log.error("error message", source="cli")
|
|
33
|
+
return 0
|
|
34
|
+
return 1
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
if __name__ == "__main__":
|
|
38
|
+
sys.exit(main())
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lauren-logging
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Structured-logging library, a drop-in upgrade from stdlib logging — JSON/pretty records, request-scoped context, file and HTTP sinks.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# lauren-logging
|
|
11
|
+
|
|
12
|
+
`lauren-logging` is a structured-logging library for Python that aims to be a
|
|
13
|
+
drop-in upgrade from the stdlib `logging` module without a heavy rewrite. It emits
|
|
14
|
+
JSON (or pretty console) records with stable field names, request-scoped context
|
|
15
|
+
(auto-injected trace_id / user_id / request_id), and sinks for stdout, files with
|
|
16
|
+
rotation, and HTTP/Loki collectors. It is for services that want machine-readable
|
|
17
|
+
logs in production but readable logs in development — and that want both from the
|
|
18
|
+
same call sites.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- `get_logger(name)` returns a logger whose `.info/.error(...)` accept a free-form
|
|
23
|
+
message plus keyword fields, all serialized as structured records.
|
|
24
|
+
- Request-scoped context via `bind(**fields)` / `with_context(...)`; child loggers
|
|
25
|
+
inherit bound fields automatically, so trace_id need not be threaded by hand.
|
|
26
|
+
- Handlers for stdout (JSON or pretty, picked by `LAUREN_PRETTY`), rotating files,
|
|
27
|
+
and an HTTP sink (Loki/Batch-format) for central collection.
|
|
28
|
+
- Sampling and redaction rules (regex-based PII masking) configured once per app.
|
|
29
|
+
- Stdlib interop: a `LaurenHandler` bridges third-party `logging` calls into
|
|
30
|
+
structured records so libraries that use stdlib still emit JSON.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install lauren-logging # core: stdout + file sinks
|
|
36
|
+
pip install "lauren-logging[loki]" # adds the HTTP/Loki sink + httpx
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from lauren_logging import get_logger, with_context
|
|
43
|
+
|
|
44
|
+
log = get_logger("billing")
|
|
45
|
+
|
|
46
|
+
with with_context(trace_id="abc123", user_id="u_42"):
|
|
47
|
+
log.info("invoice created", invoice_id="inv_9001", amount_cents=4200)
|
|
48
|
+
try:
|
|
49
|
+
1 / 0
|
|
50
|
+
except ZeroDivisionError:
|
|
51
|
+
log.error("division failed", exc_info=True)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## API
|
|
55
|
+
|
|
56
|
+
- `get_logger(name) -> Logger` — main entry; `.info/.warning/.error(msg, **fields)`.
|
|
57
|
+
- `with_context(**fields)` — context manager pushing fields onto the current scope.
|
|
58
|
+
- `Logger.bind(**fields) -> Logger` — child logger with permanent fields.
|
|
59
|
+
- `add_handler(handler)` — `StreamHandler`, `RotatingFileHandler`, `HttpSink`.
|
|
60
|
+
|
|
61
|
+
## Configuration
|
|
62
|
+
|
|
63
|
+
`LAUREN_LEVEL` (default `INFO`), `LAUREN_PRETTY` (truthy → color console),
|
|
64
|
+
`LAUREN_JSON` (force JSON), and `LAUREN_SINK` (`stdout|file|loki`) are honored out of
|
|
65
|
+
the box; a `lauren-logging.toml` provides per-logger redaction and sampling rules.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/lauren_logging/__init__.py
|
|
4
|
+
src/lauren_logging/cli.py
|
|
5
|
+
src/lauren_logging.egg-info/PKG-INFO
|
|
6
|
+
src/lauren_logging.egg-info/SOURCES.txt
|
|
7
|
+
src/lauren_logging.egg-info/dependency_links.txt
|
|
8
|
+
src/lauren_logging.egg-info/entry_points.txt
|
|
9
|
+
src/lauren_logging.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lauren_logging
|