structguru 1.6.0__tar.gz → 1.7.1__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.
Files changed (52) hide show
  1. {structguru-1.6.0 → structguru-1.7.1}/Cargo.lock +3 -2
  2. {structguru-1.6.0 → structguru-1.7.1}/Cargo.toml +1 -1
  3. {structguru-1.6.0 → structguru-1.7.1}/PKG-INFO +37 -8
  4. {structguru-1.6.0 → structguru-1.7.1}/README.md +36 -7
  5. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/Cargo.toml +3 -0
  6. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/filter.rs +39 -4
  7. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/lib.rs +25 -0
  8. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/render.rs +15 -1
  9. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/value.rs +26 -0
  10. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/worker.rs +421 -66
  11. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/conversion.rs +117 -11
  12. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/dispatch.rs +228 -41
  13. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/filter.rs +5 -0
  14. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/lib.rs +6 -0
  15. structguru-1.7.1/crates/structguru-py/src/pipeline.rs +350 -0
  16. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/rendering.rs +27 -14
  17. structguru-1.7.1/crates/structguru-py/src/submission.rs +199 -0
  18. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/template.rs +135 -5
  19. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/writer.rs +43 -21
  20. {structguru-1.6.0 → structguru-1.7.1}/pyproject.toml +6 -6
  21. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/__init__.py +1 -1
  22. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/_native_dispatch.py +17 -1
  23. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/_runtime.py +179 -96
  24. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/core.py +72 -61
  25. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/exceptions.py +6 -4
  26. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/_util.py +1 -1
  27. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/celery.py +100 -33
  28. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/requests.py +9 -16
  29. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/sentry.py +24 -6
  30. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/stdlib.py +77 -9
  31. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/settings.py +5 -2
  32. {structguru-1.6.0 → structguru-1.7.1}/LICENSE +0 -0
  33. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-core/src/clock.rs +0 -0
  34. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/Cargo.toml +0 -0
  35. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/exception.rs +0 -0
  36. {structguru-1.6.0 → structguru-1.7.1}/crates/structguru-py/src/local_repr.rs +0 -0
  37. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/_contextvars.py +0 -0
  38. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/_levels.py +0 -0
  39. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/_native_env.py +0 -0
  40. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/config.py +0 -0
  41. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/__init__.py +0 -0
  42. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/_stdlib_env.py +0 -0
  43. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/asgi.py +0 -0
  44. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/django.py +0 -0
  45. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/flask.py +0 -0
  46. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/grpc.py +0 -0
  47. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/httpx.py +0 -0
  48. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/integrations/sqlalchemy.py +0 -0
  49. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/metrics.py +0 -0
  50. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/otel.py +0 -0
  51. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/py.typed +0 -0
  52. {structguru-1.6.0 → structguru-1.7.1}/src/structguru/redaction.py +0 -0
@@ -245,10 +245,11 @@ dependencies = [
245
245
 
246
246
  [[package]]
247
247
  name = "structguru-core"
248
- version = "1.6.0"
248
+ version = "1.7.1"
249
249
  dependencies = [
250
250
  "fancy-regex",
251
251
  "fastrand",
252
+ "libc",
252
253
  "regex",
253
254
  "serde",
254
255
  "serde_json",
@@ -257,7 +258,7 @@ dependencies = [
257
258
 
258
259
  [[package]]
259
260
  name = "structguru-py"
260
- version = "1.6.0"
261
+ version = "1.7.1"
261
262
  dependencies = [
262
263
  "pyo3",
263
264
  "regex",
@@ -3,7 +3,7 @@ members = ["crates/structguru-core", "crates/structguru-py"]
3
3
  resolver = "2"
4
4
 
5
5
  [workspace.package]
6
- version = "1.6.0"
6
+ version = "1.7.1"
7
7
  edition = "2024"
8
8
  rust-version = "1.89"
9
9
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: structguru
3
- Version: 1.6.0
3
+ Version: 1.7.1
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -55,7 +55,7 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
55
55
  - **Structured JSON output** in production (rendered natively in Rust for speed)
56
56
  - **Pretty colored console** output in development
57
57
  - **Context management** — `bind()` for persistent context, `contextualize()` for request-scoped context
58
- - **Sentry integration** — redacted breadcrumbs/events with raw exceptions preserved for capture
58
+ - **Sentry integration** — redacted breadcrumbs/events with raw exception capture available by opt-in
59
59
  - **stdlib interop** — `logger.add()` sinks can also receive third-party `logging` records
60
60
  - **RFC 5424 severity codes** included in every log record
61
61
  - **Native Rust runtime** — rendering and output run through the bundled abi3 extension
@@ -143,7 +143,7 @@ options, not buffered records, counters, stdlib bridge state, or `logger.add()`
143
143
  Those registered sinks survive reconfiguration. Streams and callbacks retain their identity.
144
144
 
145
145
  Levels accept case-insensitive names (including `NOTSET`) or non-negative integer
146
- thresholds. Unknown names, booleans and negative integers raise `ValueError`.
146
+ thresholds up to `2**63 - 1`. Unknown names, booleans and out-of-range integers raise `ValueError`.
147
147
 
148
148
  ### Environment configuration
149
149
 
@@ -173,6 +173,8 @@ The stdlib bridge retains its separate `STRUCTGURU_STDLIB_*` options and explici
173
173
  ### Log levels
174
174
 
175
175
  ```python
176
+ from structguru import logger
177
+
176
178
  logger.debug("Debug message")
177
179
  logger.info("Info message")
178
180
  logger.warning("Warning message")
@@ -191,6 +193,8 @@ logger.fatal("Alias for critical")
191
193
  Arguments used in `str.format` placeholders are consumed by formatting (matching loguru behaviour). Extra kwargs that are **not** in any placeholder are forwarded as structured fields:
192
194
 
193
195
  ```python
196
+ from structguru import logger
197
+
194
198
  logger.info("User {user_id} logged in", user_id=42, ip="10.0.0.1")
195
199
  # message: "User 42 logged in"
196
200
  # ip: "10.0.0.1" (extra kwarg kept as structured field)
@@ -213,6 +217,8 @@ message whose `str()` raises, is logged raw or as a placeholder with a one-shot
213
217
  ### Bound context
214
218
 
215
219
  ```python
220
+ from structguru import logger
221
+
216
222
  log = logger.bind(request_id="abc-123", user="alice")
217
223
  log.info("Processing request") # includes request_id and user
218
224
  log.info("Request complete") # same context carried through
@@ -221,6 +227,8 @@ log.info("Request complete") # same context carried through
221
227
  ### Request-scoped context
222
228
 
223
229
  ```python
230
+ from structguru import logger
231
+
224
232
  with logger.contextualize(request_id="abc-123"):
225
233
  logger.info("Handling request") # includes request_id
226
234
  do_work() # any logging inside also gets request_id
@@ -230,6 +238,8 @@ with logger.contextualize(request_id="abc-123"):
230
238
  ### Exception logging
231
239
 
232
240
  ```python
241
+ from structguru import logger
242
+
233
243
  try:
234
244
  risky_operation()
235
245
  except Exception:
@@ -242,8 +252,10 @@ logger.opt(exception=True).error("Something went wrong")
242
252
  ### Sink management
243
253
 
244
254
  ```python
255
+ from structguru import logger
256
+
245
257
  # Add a file sink
246
- handler_id = logger.add("/var/log/app.log", level="ERROR")
258
+ handler_id = logger.add("app.log", level="ERROR")
247
259
 
248
260
  # Add a callable sink
249
261
  logger.add(lambda msg: send_to_monitoring(msg), level="CRITICAL")
@@ -259,7 +271,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
259
271
  Removing an id that names no active sink raises `ValueError` (a non-integer raises
260
272
  `TypeError`), as in loguru; `remove()` without an id removes the sinks added through
261
273
  that logger and its `bind()`/`opt()` children. `level` accepts a name or a non-negative
262
- integer and raises `ValueError` for anything else, like `configure(level=...)`.
274
+ integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
263
275
  A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
264
276
  wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
265
277
 
@@ -290,7 +302,7 @@ been written:
290
302
  ```python
291
303
  import structguru
292
304
 
293
- logger.info("checkpoint")
305
+ structguru.logger.info("checkpoint")
294
306
  structguru.flush() # returns once the line has reached its sink
295
307
  ```
296
308
 
@@ -300,6 +312,8 @@ structguru.flush() # returns once the line has reached its sink
300
312
  (colored, human-readable development output).
301
313
 
302
314
  ```python
315
+ from structguru import update
316
+
303
317
  # JSON (production)
304
318
  update(service="myapp", format="json")
305
319
  # → {"logger":"...","level":"INFO","severity":6,"timestamp":"...","service":"myapp","message":"..."}
@@ -344,6 +358,8 @@ backtrack limit, it is redacted entirely (fail-closed) rather than emitted
344
358
  unchecked.
345
359
 
346
360
  ```python
361
+ from structguru import update
362
+
347
363
  update(
348
364
  sensitive_patterns=[r"(?<=password=)\S+"],
349
365
  allow_backtracking_patterns=True,
@@ -394,6 +410,8 @@ traceback about five times faster and matches what CPython prints under
394
410
  `PYTHONNODEBUGRANGES=1`:
395
411
 
396
412
  ```python
413
+ from structguru import update
414
+
397
415
  update(exception_carets=False)
398
416
  ```
399
417
 
@@ -492,12 +510,12 @@ Behavior notes:
492
510
  - **Sampling & rate limiting** (`sample_rate`, `rate_limit_max`, `rate_limit_period`) are applied as native pre-render filters — dropped records cost zero rendering. `sampled` and `rate_limited` counters are distinct from the transport `dropped` counter. `sample_max_level` restricts sampling to records at or below that level; more severe records always pass.
493
511
  - **Metric hooks** (`metric_processor=...`) invoke a structlog-style processor (e.g. `MetricProcessor`) for every *kept* record on the caller's thread, with `(None, method, {"event": message, **fields})`; the message stays in `"event"` even when a field has that name. Dropped records (level/sampling/rate-limit) never reach it; hook errors are swallowed.
494
512
  - **Fork/shutdown safe** — the writer is flushed on exit and respawned in forked children (gunicorn/celery prefork). The exit drain is registered when structguru is imported, so `atexit` handlers registered afterwards can still log. Rotating-file writers sharing a path coordinate through an owner-only `.lock` sidecar; distributed hosts should still prefer stdout and an external collector.
495
- - **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which see each local's full rendering before it is truncated to `exception_max_local_repr`. Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
513
+ - **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which scan a bounded rendering prefix of at most `exception_max_local_repr + 4096` characters before final truncation (depth and item limits also apply; patterns needing later context can miss visible text). Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
496
514
  - **`stack_info` is supported natively**: the stack is captured in Python and rendered in the same position as `StackInfoRenderer` (`stack` between `service` and `message`). Unlike the standard path, the stack ends at the *user's* calling frame (frames of the `structguru` package are skipped, the way structlog skips its own).
497
515
  - **Console mode** (`format="console"`): renders colored, human-readable lines instead of JSON — structguru's own stable dev format (`<timestamp> [<LEVEL>] <message> k=v`), with ANSI colors by default on a TTY. Override with `colors=True/False`. String values are double-quoted with `"` and `\` escaped, keys containing spaces, `=`, quotes, or backslashes are quoted, and control characters, U+2028/U+2029, and bidirectional controls are escaped everywhere, so a field key or value cannot forge another field or line. Floats use the JSON renderer's text (`1.0`, `1e+300`); the stack and a formatted `exception` follow as indented blocks.
498
516
  - **File sinks** (`file_path=...`): write to a rotating file natively. Defaults mirror `RotatingFileHandler` (50 MB, 5 backups); configure via `file_max_bytes`/`file_backup_count`. Set `also_stdout=True` to mirror output to both file and stdout (e.g. container + persistent log).
499
517
  - **Callable sinks** (`callable_sinks=[fn, ...]`): use a bounded queue (`callable_queue_maxsize=1024`). `overflow="block"` provides lossless backpressure; `overflow="drop"` reports `callable_dropped` metrics. One background thread at a time calls the sinks, in log order, also across reconfiguration; `logger.add()` never waits for the queue. Sink exceptions are counted in `callable_errors` with a rate-limited warning. Flush and lifecycle operations drain queued calls; a sink that makes no progress for 10 seconds is abandoned with a warning instead of blocking them.
500
- - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event and raw `exc_info` only for exception capture.
518
+ - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
501
519
  - **Scope**: the native renderer covers JSON and console rendering, file/stdout/callable sinks, redaction, sampling/rate limiting, metrics, exceptions, and stack information. `logger.add()` sinks receive native and stdlib records.
502
520
 
503
521
  Shutdown and reconfiguration drain records already accepted by the native queue.
@@ -516,6 +534,8 @@ Calls begun while logging is disabled are no-ops and are not counted. See the [l
516
534
  ### ASGI (FastAPI / Starlette)
517
535
 
518
536
  ```python
537
+ from fastapi import FastAPI
538
+
519
539
  from structguru.integrations.asgi import StructguruMiddleware
520
540
 
521
541
  app = FastAPI()
@@ -541,6 +561,8 @@ setup_celery_logging(propagate_context=True, context_keys=["request_id"])
541
561
  ### Flask
542
562
 
543
563
  ```python
564
+ from flask import Flask
565
+
544
566
  from structguru.integrations.flask import setup_flask_logging
545
567
 
546
568
  app = Flask(__name__)
@@ -569,6 +591,10 @@ setup_query_logging(engine, slow_threshold_ms=100, log_all=False)
569
591
  ### gRPC
570
592
 
571
593
  ```python
594
+ from concurrent import futures
595
+
596
+ import grpc
597
+
572
598
  from structguru.integrations.grpc import StructguruInterceptor
573
599
 
574
600
  server = grpc.server(
@@ -669,7 +695,10 @@ The [documentation](docs/index.md) follows [Diátaxis](https://diataxis.fr/):
669
695
  - **[Reference](docs/reference/index.md)** — API, settings and environment variables, record format, metrics, and integration details.
670
696
  - **[Explanation](docs/explanation/index.md)** — Architecture, delivery guarantees, context propagation, and redaction design.
671
697
  - **[Full-stack Example](examples/full_stack_fastapi/main.py)** — FastAPI + Celery + SQLAlchemy in action.
698
+ - **[Granian + FastAPI Example](examples/granian_fastapi/main.py)** — Launch through Granian's Python API with structured server and request logs.
672
699
  - **[Existing-loggers Example](examples/stdlib_existing_loggers/main.py)** — Configure the stdlib policy and bridge replacement from code or environment.
700
+ - **[Context-propagation Example](examples/context_propagation/main.py)** — Carry request fields through async tasks and a thread pool.
701
+ - **[Sinks and Testing Example](examples/sinks_and_testing/main.py)** — Capture, redact, and assert on rendered records with deterministic cleanup.
673
702
 
674
703
  ## Development
675
704
 
@@ -10,7 +10,7 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
10
10
  - **Structured JSON output** in production (rendered natively in Rust for speed)
11
11
  - **Pretty colored console** output in development
12
12
  - **Context management** — `bind()` for persistent context, `contextualize()` for request-scoped context
13
- - **Sentry integration** — redacted breadcrumbs/events with raw exceptions preserved for capture
13
+ - **Sentry integration** — redacted breadcrumbs/events with raw exception capture available by opt-in
14
14
  - **stdlib interop** — `logger.add()` sinks can also receive third-party `logging` records
15
15
  - **RFC 5424 severity codes** included in every log record
16
16
  - **Native Rust runtime** — rendering and output run through the bundled abi3 extension
@@ -98,7 +98,7 @@ options, not buffered records, counters, stdlib bridge state, or `logger.add()`
98
98
  Those registered sinks survive reconfiguration. Streams and callbacks retain their identity.
99
99
 
100
100
  Levels accept case-insensitive names (including `NOTSET`) or non-negative integer
101
- thresholds. Unknown names, booleans and negative integers raise `ValueError`.
101
+ thresholds up to `2**63 - 1`. Unknown names, booleans and out-of-range integers raise `ValueError`.
102
102
 
103
103
  ### Environment configuration
104
104
 
@@ -128,6 +128,8 @@ The stdlib bridge retains its separate `STRUCTGURU_STDLIB_*` options and explici
128
128
  ### Log levels
129
129
 
130
130
  ```python
131
+ from structguru import logger
132
+
131
133
  logger.debug("Debug message")
132
134
  logger.info("Info message")
133
135
  logger.warning("Warning message")
@@ -146,6 +148,8 @@ logger.fatal("Alias for critical")
146
148
  Arguments used in `str.format` placeholders are consumed by formatting (matching loguru behaviour). Extra kwargs that are **not** in any placeholder are forwarded as structured fields:
147
149
 
148
150
  ```python
151
+ from structguru import logger
152
+
149
153
  logger.info("User {user_id} logged in", user_id=42, ip="10.0.0.1")
150
154
  # message: "User 42 logged in"
151
155
  # ip: "10.0.0.1" (extra kwarg kept as structured field)
@@ -168,6 +172,8 @@ message whose `str()` raises, is logged raw or as a placeholder with a one-shot
168
172
  ### Bound context
169
173
 
170
174
  ```python
175
+ from structguru import logger
176
+
171
177
  log = logger.bind(request_id="abc-123", user="alice")
172
178
  log.info("Processing request") # includes request_id and user
173
179
  log.info("Request complete") # same context carried through
@@ -176,6 +182,8 @@ log.info("Request complete") # same context carried through
176
182
  ### Request-scoped context
177
183
 
178
184
  ```python
185
+ from structguru import logger
186
+
179
187
  with logger.contextualize(request_id="abc-123"):
180
188
  logger.info("Handling request") # includes request_id
181
189
  do_work() # any logging inside also gets request_id
@@ -185,6 +193,8 @@ with logger.contextualize(request_id="abc-123"):
185
193
  ### Exception logging
186
194
 
187
195
  ```python
196
+ from structguru import logger
197
+
188
198
  try:
189
199
  risky_operation()
190
200
  except Exception:
@@ -197,8 +207,10 @@ logger.opt(exception=True).error("Something went wrong")
197
207
  ### Sink management
198
208
 
199
209
  ```python
210
+ from structguru import logger
211
+
200
212
  # Add a file sink
201
- handler_id = logger.add("/var/log/app.log", level="ERROR")
213
+ handler_id = logger.add("app.log", level="ERROR")
202
214
 
203
215
  # Add a callable sink
204
216
  logger.add(lambda msg: send_to_monitoring(msg), level="CRITICAL")
@@ -214,7 +226,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
214
226
  Removing an id that names no active sink raises `ValueError` (a non-integer raises
215
227
  `TypeError`), as in loguru; `remove()` without an id removes the sinks added through
216
228
  that logger and its `bind()`/`opt()` children. `level` accepts a name or a non-negative
217
- integer and raises `ValueError` for anything else, like `configure(level=...)`.
229
+ integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
218
230
  A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
219
231
  wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
220
232
 
@@ -245,7 +257,7 @@ been written:
245
257
  ```python
246
258
  import structguru
247
259
 
248
- logger.info("checkpoint")
260
+ structguru.logger.info("checkpoint")
249
261
  structguru.flush() # returns once the line has reached its sink
250
262
  ```
251
263
 
@@ -255,6 +267,8 @@ structguru.flush() # returns once the line has reached its sink
255
267
  (colored, human-readable development output).
256
268
 
257
269
  ```python
270
+ from structguru import update
271
+
258
272
  # JSON (production)
259
273
  update(service="myapp", format="json")
260
274
  # → {"logger":"...","level":"INFO","severity":6,"timestamp":"...","service":"myapp","message":"..."}
@@ -299,6 +313,8 @@ backtrack limit, it is redacted entirely (fail-closed) rather than emitted
299
313
  unchecked.
300
314
 
301
315
  ```python
316
+ from structguru import update
317
+
302
318
  update(
303
319
  sensitive_patterns=[r"(?<=password=)\S+"],
304
320
  allow_backtracking_patterns=True,
@@ -349,6 +365,8 @@ traceback about five times faster and matches what CPython prints under
349
365
  `PYTHONNODEBUGRANGES=1`:
350
366
 
351
367
  ```python
368
+ from structguru import update
369
+
352
370
  update(exception_carets=False)
353
371
  ```
354
372
 
@@ -447,12 +465,12 @@ Behavior notes:
447
465
  - **Sampling & rate limiting** (`sample_rate`, `rate_limit_max`, `rate_limit_period`) are applied as native pre-render filters — dropped records cost zero rendering. `sampled` and `rate_limited` counters are distinct from the transport `dropped` counter. `sample_max_level` restricts sampling to records at or below that level; more severe records always pass.
448
466
  - **Metric hooks** (`metric_processor=...`) invoke a structlog-style processor (e.g. `MetricProcessor`) for every *kept* record on the caller's thread, with `(None, method, {"event": message, **fields})`; the message stays in `"event"` even when a field has that name. Dropped records (level/sampling/rate-limit) never reach it; hook errors are swallowed.
449
467
  - **Fork/shutdown safe** — the writer is flushed on exit and respawned in forked children (gunicorn/celery prefork). The exit drain is registered when structguru is imported, so `atexit` handlers registered afterwards can still log. Rotating-file writers sharing a path coordinate through an owner-only `.lock` sidecar; distributed hosts should still prefer stdout and an external collector.
450
- - **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which see each local's full rendering before it is truncated to `exception_max_local_repr`. Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
468
+ - **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which scan a bounded rendering prefix of at most `exception_max_local_repr + 4096` characters before final truncation (depth and item limits also apply; patterns needing later context can miss visible text). Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
451
469
  - **`stack_info` is supported natively**: the stack is captured in Python and rendered in the same position as `StackInfoRenderer` (`stack` between `service` and `message`). Unlike the standard path, the stack ends at the *user's* calling frame (frames of the `structguru` package are skipped, the way structlog skips its own).
452
470
  - **Console mode** (`format="console"`): renders colored, human-readable lines instead of JSON — structguru's own stable dev format (`<timestamp> [<LEVEL>] <message> k=v`), with ANSI colors by default on a TTY. Override with `colors=True/False`. String values are double-quoted with `"` and `\` escaped, keys containing spaces, `=`, quotes, or backslashes are quoted, and control characters, U+2028/U+2029, and bidirectional controls are escaped everywhere, so a field key or value cannot forge another field or line. Floats use the JSON renderer's text (`1.0`, `1e+300`); the stack and a formatted `exception` follow as indented blocks.
453
471
  - **File sinks** (`file_path=...`): write to a rotating file natively. Defaults mirror `RotatingFileHandler` (50 MB, 5 backups); configure via `file_max_bytes`/`file_backup_count`. Set `also_stdout=True` to mirror output to both file and stdout (e.g. container + persistent log).
454
472
  - **Callable sinks** (`callable_sinks=[fn, ...]`): use a bounded queue (`callable_queue_maxsize=1024`). `overflow="block"` provides lossless backpressure; `overflow="drop"` reports `callable_dropped` metrics. One background thread at a time calls the sinks, in log order, also across reconfiguration; `logger.add()` never waits for the queue. Sink exceptions are counted in `callable_errors` with a rate-limited warning. Flush and lifecycle operations drain queued calls; a sink that makes no progress for 10 seconds is abandoned with a warning instead of blocking them.
455
- - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event and raw `exc_info` only for exception capture.
473
+ - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
456
474
  - **Scope**: the native renderer covers JSON and console rendering, file/stdout/callable sinks, redaction, sampling/rate limiting, metrics, exceptions, and stack information. `logger.add()` sinks receive native and stdlib records.
457
475
 
458
476
  Shutdown and reconfiguration drain records already accepted by the native queue.
@@ -471,6 +489,8 @@ Calls begun while logging is disabled are no-ops and are not counted. See the [l
471
489
  ### ASGI (FastAPI / Starlette)
472
490
 
473
491
  ```python
492
+ from fastapi import FastAPI
493
+
474
494
  from structguru.integrations.asgi import StructguruMiddleware
475
495
 
476
496
  app = FastAPI()
@@ -496,6 +516,8 @@ setup_celery_logging(propagate_context=True, context_keys=["request_id"])
496
516
  ### Flask
497
517
 
498
518
  ```python
519
+ from flask import Flask
520
+
499
521
  from structguru.integrations.flask import setup_flask_logging
500
522
 
501
523
  app = Flask(__name__)
@@ -524,6 +546,10 @@ setup_query_logging(engine, slow_threshold_ms=100, log_all=False)
524
546
  ### gRPC
525
547
 
526
548
  ```python
549
+ from concurrent import futures
550
+
551
+ import grpc
552
+
527
553
  from structguru.integrations.grpc import StructguruInterceptor
528
554
 
529
555
  server = grpc.server(
@@ -624,7 +650,10 @@ The [documentation](docs/index.md) follows [Diátaxis](https://diataxis.fr/):
624
650
  - **[Reference](docs/reference/index.md)** — API, settings and environment variables, record format, metrics, and integration details.
625
651
  - **[Explanation](docs/explanation/index.md)** — Architecture, delivery guarantees, context propagation, and redaction design.
626
652
  - **[Full-stack Example](examples/full_stack_fastapi/main.py)** — FastAPI + Celery + SQLAlchemy in action.
653
+ - **[Granian + FastAPI Example](examples/granian_fastapi/main.py)** — Launch through Granian's Python API with structured server and request logs.
627
654
  - **[Existing-loggers Example](examples/stdlib_existing_loggers/main.py)** — Configure the stdlib policy and bridge replacement from code or environment.
655
+ - **[Context-propagation Example](examples/context_propagation/main.py)** — Carry request fields through async tasks and a thread pool.
656
+ - **[Sinks and Testing Example](examples/sinks_and_testing/main.py)** — Capture, redact, and assert on rendered records with deterministic cleanup.
628
657
 
629
658
  ## Development
630
659
 
@@ -20,3 +20,6 @@ time.workspace = true
20
20
  regex.workspace = true
21
21
  fancy-regex.workspace = true
22
22
  fastrand.workspace = true
23
+
24
+ [target.'cfg(unix)'.dependencies]
25
+ libc = "0.2"
@@ -127,7 +127,10 @@ impl RateLimiter {
127
127
  }
128
128
 
129
129
  fn allow_key(&self, key: &str, now: Instant) -> Decision {
130
- let mut state = self.buckets.lock().expect("rate limiter state poisoned");
130
+ let mut state = self
131
+ .buckets
132
+ .lock()
133
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
131
134
  let cutoff = now.checked_sub(self.period);
132
135
 
133
136
  // Prune the candidate bucket up to the window edge.
@@ -170,7 +173,7 @@ impl RateLimiter {
170
173
  fn tracked_keys(&self) -> usize {
171
174
  self.buckets
172
175
  .lock()
173
- .expect("rate limiter state poisoned")
176
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
174
177
  .timestamps
175
178
  .len()
176
179
  }
@@ -272,7 +275,10 @@ impl Pipeline {
272
275
  }
273
276
  };
274
277
  if decision == Decision::Drop {
275
- let mut stats = self.stats.lock().expect("filter stats poisoned");
278
+ let mut stats = self
279
+ .stats
280
+ .lock()
281
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
276
282
  if sampled {
277
283
  stats.sampled += 1;
278
284
  }
@@ -292,7 +298,10 @@ impl Pipeline {
292
298
 
293
299
  /// Snapshot of drop counters.
294
300
  pub fn stats(&self) -> FilterStats {
295
- *self.stats.lock().expect("filter stats poisoned")
301
+ *self
302
+ .stats
303
+ .lock()
304
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
296
305
  }
297
306
  }
298
307
 
@@ -300,6 +309,32 @@ impl Pipeline {
300
309
  mod tests {
301
310
  use super::*;
302
311
 
312
+ #[test]
313
+ fn poisoned_rate_state_keeps_enforcing_the_existing_window() {
314
+ let limiter = RateLimiter::new(1, Duration::from_secs(60));
315
+ assert_eq!(limiter.allow("same", 20), Decision::Keep);
316
+ let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
317
+ let _guard = limiter.buckets.lock().unwrap();
318
+ panic!("injected rate state poison");
319
+ }));
320
+ assert!(poisoned.is_err());
321
+ assert_eq!(limiter.allow("same", 20), Decision::Drop);
322
+ assert_eq!(limiter.allow("other", 20), Decision::Keep);
323
+ assert_eq!(limiter.tracked_keys(), 2);
324
+ }
325
+
326
+ #[test]
327
+ fn poisoned_filter_stats_remain_readable_and_incrementable() {
328
+ let pipeline = Pipeline::new(0.0, None, None, Duration::from_secs(1));
329
+ let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
330
+ let _guard = pipeline.stats.lock().unwrap();
331
+ panic!("injected filter statistics poison");
332
+ }));
333
+ assert!(poisoned.is_err());
334
+ assert!(!pipeline.allow("record", 20));
335
+ assert_eq!(pipeline.stats().sampled, 1);
336
+ }
337
+
303
338
  #[test]
304
339
  fn sampler_rate_zero_drops_all() {
305
340
  let s = Sampler::new(0.0, None);
@@ -56,6 +56,19 @@ pub fn level_number(method: &str) -> Option<u8> {
56
56
  .map(|(_, number)| *number)
57
57
  }
58
58
 
59
+ /// Map a numeric stdlib level to the canonical method at or below it.
60
+ pub fn method_for_level_number(levelno: i64) -> &'static str {
61
+ match levelno {
62
+ 50.. => "critical",
63
+ 40.. => "error",
64
+ 30.. => "warning",
65
+ 20.. => "info",
66
+ 10.. => "debug",
67
+ 5.. => "trace",
68
+ _ => "debug",
69
+ }
70
+ }
71
+
59
72
  /// Normalize a structguru/loguru-style level name to the canonical field value.
60
73
  ///
61
74
  /// Unknown levels follow the current Python processor contract: uppercase the
@@ -104,6 +117,18 @@ mod tests {
104
117
  assert_eq!(level_number("notice"), None);
105
118
  }
106
119
 
120
+ #[test]
121
+ fn numeric_levels_select_their_stdlib_method_band() {
122
+ assert_eq!(method_for_level_number(-1), "debug");
123
+ assert_eq!(method_for_level_number(5), "trace");
124
+ assert_eq!(method_for_level_number(10), "debug");
125
+ assert_eq!(method_for_level_number(25), "info");
126
+ assert_eq!(method_for_level_number(35), "warning");
127
+ assert_eq!(method_for_level_number(45), "error");
128
+ assert_eq!(method_for_level_number(50), "critical");
129
+ assert_eq!(method_for_level_number(i64::MAX), "critical");
130
+ }
131
+
107
132
  #[test]
108
133
  fn level_table_lists_the_canonical_method_first_per_number() {
109
134
  let mut seen = std::collections::HashSet::new();
@@ -164,6 +164,18 @@ fn is_sensitive(key: &str, keys: &[impl AsRef<str>]) -> bool {
164
164
  /// `RedactingProcessor`: no value-pattern matching).
165
165
  fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
166
166
  match value {
167
+ Value::Keyed {
168
+ aliases,
169
+ value: child,
170
+ } => {
171
+ let redacted = if aliases.iter().any(|alias| is_sensitive(alias, keys)) {
172
+ Value::String(REDACTED.to_owned())
173
+ } else {
174
+ redact(child, keys);
175
+ std::mem::replace(child.as_mut(), Value::Null)
176
+ };
177
+ *value = redacted;
178
+ }
167
179
  Value::Map(entries) => {
168
180
  for (key, child) in entries.iter_mut() {
169
181
  if is_sensitive(key, keys) {
@@ -204,6 +216,7 @@ fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
204
216
  /// secret — `password=(\S+)` with `$1[REDACTED]` would re-emit the secret.
205
217
  fn redact_patterns(value: &mut Value, patterns: &[RedactionPattern], replacement: &str) {
206
218
  match value {
219
+ Value::Keyed { value, .. } => redact_patterns(value, patterns, replacement),
207
220
  Value::Map(entries) => {
208
221
  let mut renamed = false;
209
222
  for (key, child) in entries.iter_mut() {
@@ -456,7 +469,7 @@ fn is_console_unsafe(ch: char) -> bool {
456
469
  | '\u{200E}'
457
470
  | '\u{200F}'
458
471
  | '\u{202A}'..='\u{202E}'
459
- | '\u{2066}'..='\u{2069}'
472
+ | '\u{2066}'..='\u{206F}'
460
473
  )
461
474
  }
462
475
 
@@ -583,6 +596,7 @@ fn display_value(value: &Value, buf: &mut String) {
583
596
  buf.push('}');
584
597
  }
585
598
  Value::Raw(json) => buf.push_str(json), // already-serialized; emit verbatim
599
+ Value::Keyed { value, .. } => display_value(value, buf),
586
600
  }
587
601
  }
588
602
 
@@ -12,6 +12,12 @@ pub enum Value {
12
12
  String(String),
13
13
  List(Vec<Value>),
14
14
  Map(Vec<(String, Value)>),
15
+ /// Original mapping-key names retained only for redaction. Serialization
16
+ /// and structural metrics expose the value, never this internal metadata.
17
+ Keyed {
18
+ aliases: Box<[String]>,
19
+ value: Box<Value>,
20
+ },
15
21
  /// Pre-serialized, already-valid JSON emitted verbatim.
16
22
  ///
17
23
  /// Used for integers outside the `i64` range: the boundary emits their
@@ -39,6 +45,10 @@ impl Value {
39
45
  }
40
46
 
41
47
  fn update_stats(&self, depth: usize, stats: &mut ValueStats) {
48
+ if let Value::Keyed { value, .. } = self {
49
+ value.update_stats(depth, stats);
50
+ return;
51
+ }
42
52
  stats.nodes += 1;
43
53
  stats.max_depth = stats.max_depth.max(depth);
44
54
 
@@ -58,6 +68,7 @@ impl Value {
58
68
  | Value::Int(_)
59
69
  | Value::Float(_)
60
70
  | Value::String(_)
71
+ | Value::Keyed { .. }
61
72
  | Value::Raw(_) => {}
62
73
  }
63
74
  }
@@ -122,6 +133,7 @@ impl Serialize for Value {
122
133
  Value::Int(value) => serializer.serialize_i64(*value),
123
134
  Value::Float(value) => serializer.serialize_f64(*value),
124
135
  Value::String(value) => serializer.serialize_str(value),
136
+ Value::Keyed { value, .. } => value.serialize(serializer),
125
137
  Value::List(items) => {
126
138
  let mut seq = serializer.serialize_seq(Some(items.len()))?;
127
139
  for item in items {
@@ -149,6 +161,20 @@ impl Serialize for Value {
149
161
  mod tests {
150
162
  use super::{Value, ValueStats, collapse_duplicate_keys};
151
163
 
164
+ #[test]
165
+ fn key_alias_metadata_is_not_serialized_or_counted() {
166
+ let inner = Value::List(vec![Value::Int(42)]);
167
+ let keyed = Value::Keyed {
168
+ aliases: vec!["password".to_owned()].into_boxed_slice(),
169
+ value: Box::new(inner.clone()),
170
+ };
171
+ assert_eq!(
172
+ keyed.to_json_string().unwrap(),
173
+ inner.to_json_string().unwrap()
174
+ );
175
+ assert_eq!(keyed.stats(), inner.stats());
176
+ }
177
+
152
178
  #[test]
153
179
  fn stats_count_nested_value_nodes() {
154
180
  let value = Value::Map(vec![