structguru 1.5.0__tar.gz → 1.7.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.
Files changed (52) hide show
  1. {structguru-1.5.0 → structguru-1.7.0}/Cargo.lock +22 -32
  2. {structguru-1.5.0 → structguru-1.7.0}/Cargo.toml +3 -3
  3. {structguru-1.5.0 → structguru-1.7.0}/PKG-INFO +10 -6
  4. {structguru-1.5.0 → structguru-1.7.0}/README.md +9 -5
  5. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/Cargo.toml +3 -0
  6. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/filter.rs +39 -4
  7. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/render.rs +27 -4
  8. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/value.rs +26 -0
  9. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/worker.rs +541 -66
  10. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/conversion.rs +122 -12
  11. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/dispatch.rs +291 -70
  12. structguru-1.7.0/crates/structguru-py/src/exception.rs +33 -0
  13. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/lib.rs +8 -0
  14. structguru-1.7.0/crates/structguru-py/src/local_repr.rs +403 -0
  15. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/rendering.rs +27 -14
  16. structguru-1.7.0/crates/structguru-py/src/submission.rs +105 -0
  17. structguru-1.7.0/crates/structguru-py/src/template.rs +159 -0
  18. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/writer.rs +86 -8
  19. {structguru-1.5.0 → structguru-1.7.0}/pyproject.toml +10 -10
  20. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/__init__.py +1 -1
  21. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/_native_dispatch.py +9 -1
  22. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/_runtime.py +408 -72
  23. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/core.py +212 -100
  24. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/exceptions.py +112 -224
  25. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/_util.py +1 -1
  26. structguru-1.7.0/src/structguru/integrations/celery.py +326 -0
  27. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/grpc.py +14 -26
  28. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/requests.py +34 -27
  29. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/sentry.py +24 -6
  30. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/sqlalchemy.py +6 -1
  31. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/stdlib.py +34 -13
  32. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/settings.py +5 -2
  33. structguru-1.5.0/src/structguru/integrations/celery.py +0 -244
  34. {structguru-1.5.0 → structguru-1.7.0}/LICENSE +0 -0
  35. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/clock.rs +0 -0
  36. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-core/src/lib.rs +0 -0
  37. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/Cargo.toml +0 -0
  38. {structguru-1.5.0 → structguru-1.7.0}/crates/structguru-py/src/filter.rs +0 -0
  39. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/_contextvars.py +0 -0
  40. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/_levels.py +0 -0
  41. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/_native_env.py +0 -0
  42. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/config.py +0 -0
  43. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/__init__.py +0 -0
  44. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/_stdlib_env.py +0 -0
  45. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/asgi.py +0 -0
  46. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/django.py +0 -0
  47. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/flask.py +0 -0
  48. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/integrations/httpx.py +0 -0
  49. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/metrics.py +0 -0
  50. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/otel.py +0 -0
  51. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/py.typed +0 -0
  52. {structguru-1.5.0 → structguru-1.7.0}/src/structguru/redaction.py +0 -0
@@ -28,15 +28,15 @@ checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
28
28
 
29
29
  [[package]]
30
30
  name = "deranged"
31
- version = "0.5.8"
31
+ version = "0.5.9"
32
32
  source = "registry+https://github.com/rust-lang/crates.io-index"
33
- checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
33
+ checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
34
34
 
35
35
  [[package]]
36
36
  name = "fancy-regex"
37
- version = "0.19.2"
37
+ version = "0.20.0"
38
38
  source = "registry+https://github.com/rust-lang/crates.io-index"
39
- checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
39
+ checksum = "20ed7f62ce0ae0da1a8b93c3c7104ab7e0760a74491e097c701fff966e945390"
40
40
  dependencies = [
41
41
  "bit-set",
42
42
  "regex-automata",
@@ -63,9 +63,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
63
63
 
64
64
  [[package]]
65
65
  name = "libc"
66
- version = "0.2.190"
66
+ version = "0.2.191"
67
67
  source = "registry+https://github.com/rust-lang/crates.io-index"
68
- checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
68
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
69
69
 
70
70
  [[package]]
71
71
  name = "memchr"
@@ -108,9 +108,9 @@ dependencies = [
108
108
 
109
109
  [[package]]
110
110
  name = "pyo3"
111
- version = "0.29.3"
111
+ version = "0.30.1"
112
112
  source = "registry+https://github.com/rust-lang/crates.io-index"
113
- checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655"
113
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
114
114
  dependencies = [
115
115
  "libc",
116
116
  "once_cell",
@@ -122,18 +122,18 @@ dependencies = [
122
122
 
123
123
  [[package]]
124
124
  name = "pyo3-build-config"
125
- version = "0.29.3"
125
+ version = "0.30.1"
126
126
  source = "registry+https://github.com/rust-lang/crates.io-index"
127
- checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb"
127
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
128
128
  dependencies = [
129
129
  "target-lexicon",
130
130
  ]
131
131
 
132
132
  [[package]]
133
133
  name = "pyo3-ffi"
134
- version = "0.29.3"
134
+ version = "0.30.1"
135
135
  source = "registry+https://github.com/rust-lang/crates.io-index"
136
- checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330"
136
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
137
137
  dependencies = [
138
138
  "libc",
139
139
  "pyo3-build-config",
@@ -141,26 +141,26 @@ dependencies = [
141
141
 
142
142
  [[package]]
143
143
  name = "pyo3-macros"
144
- version = "0.29.3"
144
+ version = "0.30.1"
145
145
  source = "registry+https://github.com/rust-lang/crates.io-index"
146
- checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6"
146
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
147
147
  dependencies = [
148
148
  "proc-macro2",
149
149
  "pyo3-macros-backend",
150
150
  "quote",
151
- "syn 2.0.119",
151
+ "syn",
152
152
  ]
153
153
 
154
154
  [[package]]
155
155
  name = "pyo3-macros-backend"
156
- version = "0.29.3"
156
+ version = "0.30.1"
157
157
  source = "registry+https://github.com/rust-lang/crates.io-index"
158
- checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3"
158
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
159
159
  dependencies = [
160
160
  "heck",
161
161
  "proc-macro2",
162
162
  "quote",
163
- "syn 2.0.119",
163
+ "syn",
164
164
  ]
165
165
 
166
166
  [[package]]
@@ -227,7 +227,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
227
227
  dependencies = [
228
228
  "proc-macro2",
229
229
  "quote",
230
- "syn 3.0.9",
230
+ "syn",
231
231
  ]
232
232
 
233
233
  [[package]]
@@ -245,10 +245,11 @@ dependencies = [
245
245
 
246
246
  [[package]]
247
247
  name = "structguru-core"
248
- version = "1.5.0"
248
+ version = "1.7.0"
249
249
  dependencies = [
250
250
  "fancy-regex",
251
251
  "fastrand",
252
+ "libc",
252
253
  "regex",
253
254
  "serde",
254
255
  "serde_json",
@@ -257,24 +258,13 @@ dependencies = [
257
258
 
258
259
  [[package]]
259
260
  name = "structguru-py"
260
- version = "1.5.0"
261
+ version = "1.7.0"
261
262
  dependencies = [
262
263
  "pyo3",
263
264
  "regex",
264
265
  "structguru-core",
265
266
  ]
266
267
 
267
- [[package]]
268
- name = "syn"
269
- version = "2.0.119"
270
- source = "registry+https://github.com/rust-lang/crates.io-index"
271
- checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
272
- dependencies = [
273
- "proc-macro2",
274
- "quote",
275
- "unicode-ident",
276
- ]
277
-
278
268
  [[package]]
279
269
  name = "syn"
280
270
  version = "3.0.9"
@@ -3,7 +3,7 @@ members = ["crates/structguru-core", "crates/structguru-py"]
3
3
  resolver = "2"
4
4
 
5
5
  [workspace.package]
6
- version = "1.5.0"
6
+ version = "1.7.0"
7
7
  edition = "2024"
8
8
  rust-version = "1.89"
9
9
  license = "MIT"
@@ -25,7 +25,7 @@ codegen-units = 1
25
25
  strip = true
26
26
 
27
27
  [workspace.dependencies]
28
- pyo3 = { version = "0.29.2" }
28
+ pyo3 = { version = "0.30.1" }
29
29
  serde = { version = "1.0" }
30
30
  serde_json = { version = "1.0", features = ["raw_value"] }
31
31
  time = { version = "0.3", features = ["macros", "formatting"] }
@@ -34,7 +34,7 @@ time = { version = "0.3", features = ["macros", "formatting"] }
34
34
  regex = { version = "1", default-features = false, features = ["std", "unicode"] }
35
35
  # Backtracking engine for opt-in look-around/backreference redaction patterns
36
36
  # (`allow_backtracking_patterns=True`); never used unless explicitly requested.
37
- fancy-regex = { version = "0.19", default-features = false, features = ["std", "unicode"] }
37
+ fancy-regex = { version = "0.20", default-features = false, features = ["std", "unicode"] }
38
38
  # Only a per-thread `f64` draw is needed (sampling filter). fastrand's WyRand
39
39
  # generator has no transitive dependencies on the wheel targets, unlike rand's
40
40
  # ChaCha-based thread RNG.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: structguru
3
- Version: 1.5.0
3
+ Version: 1.7.0
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
 
@@ -259,7 +259,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
259
259
  Removing an id that names no active sink raises `ValueError` (a non-integer raises
260
260
  `TypeError`), as in loguru; `remove()` without an id removes the sinks added through
261
261
  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=...)`.
262
+ integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
263
263
  A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
264
264
  wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
265
265
 
@@ -492,15 +492,18 @@ Behavior notes:
492
492
  - **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
493
  - **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
494
  - **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.
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 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
496
  - **`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
497
  - **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
498
  - **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
499
  - **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.
500
+ - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
501
501
  - **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
502
 
503
503
  Shutdown and reconfiguration drain records already accepted by the native queue.
504
+ A native or callable sink that makes no progress for 10 seconds is abandoned
505
+ with a warning instead of blocking the caller. Queued native records are
506
+ discarded, and the warning does not wait on a full stderr.
504
507
  Calls still formatting or waiting for space may be rejected when their writer closes,
505
508
  even in block mode. `lifecycle_metrics()["rejected"]` counts these native deliveries
506
509
  without queue-full warnings and survives shutdown and configuration changes; forked
@@ -560,6 +563,7 @@ MIDDLEWARE = ["structguru.integrations.django.StructguruMiddleware", ...]
560
563
  from structguru.integrations.sqlalchemy import setup_query_logging
561
564
 
562
565
  setup_query_logging(engine, slow_threshold_ms=100, log_all=False)
566
+ # query is "<omitted>" by default; pass include_query=True to log statement[:500]
563
567
  ```
564
568
 
565
569
  ### gRPC
@@ -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
 
@@ -214,7 +214,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
214
214
  Removing an id that names no active sink raises `ValueError` (a non-integer raises
215
215
  `TypeError`), as in loguru; `remove()` without an id removes the sinks added through
216
216
  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=...)`.
217
+ integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
218
218
  A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
219
219
  wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
220
220
 
@@ -447,15 +447,18 @@ Behavior notes:
447
447
  - **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
448
  - **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
449
  - **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.
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 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
451
  - **`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
452
  - **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
453
  - **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
454
  - **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.
455
+ - **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
456
456
  - **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
457
 
458
458
  Shutdown and reconfiguration drain records already accepted by the native queue.
459
+ A native or callable sink that makes no progress for 10 seconds is abandoned
460
+ with a warning instead of blocking the caller. Queued native records are
461
+ discarded, and the warning does not wait on a full stderr.
459
462
  Calls still formatting or waiting for space may be rejected when their writer closes,
460
463
  even in block mode. `lifecycle_metrics()["rejected"]` counts these native deliveries
461
464
  without queue-full warnings and survives shutdown and configuration changes; forked
@@ -515,6 +518,7 @@ MIDDLEWARE = ["structguru.integrations.django.StructguruMiddleware", ...]
515
518
  from structguru.integrations.sqlalchemy import setup_query_logging
516
519
 
517
520
  setup_query_logging(engine, slow_threshold_ms=100, log_all=False)
521
+ # query is "<omitted>" by default; pass include_query=True to log statement[:500]
518
522
  ```
519
523
 
520
524
  ### gRPC
@@ -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);
@@ -71,9 +71,8 @@ impl RedactionPattern {
71
71
  match self {
72
72
  Self::Linear(re) if re.is_match(text) => re.replace_all(text, replacement),
73
73
  Self::Linear(_) => Cow::Borrowed(text),
74
- Self::Backtracking(re) => {
75
- replace_all_backtracking(re, text, replacement).unwrap_or(Cow::Borrowed(REDACTED))
76
- }
74
+ Self::Backtracking(re) => replace_all_backtracking(re, text, replacement)
75
+ .unwrap_or_else(|| Cow::Owned(REDACTED.to_owned())),
77
76
  }
78
77
  }
79
78
  }
@@ -165,6 +164,18 @@ fn is_sensitive(key: &str, keys: &[impl AsRef<str>]) -> bool {
165
164
  /// `RedactingProcessor`: no value-pattern matching).
166
165
  fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
167
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
+ }
168
179
  Value::Map(entries) => {
169
180
  for (key, child) in entries.iter_mut() {
170
181
  if is_sensitive(key, keys) {
@@ -205,6 +216,7 @@ fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
205
216
  /// secret — `password=(\S+)` with `$1[REDACTED]` would re-emit the secret.
206
217
  fn redact_patterns(value: &mut Value, patterns: &[RedactionPattern], replacement: &str) {
207
218
  match value {
219
+ Value::Keyed { value, .. } => redact_patterns(value, patterns, replacement),
208
220
  Value::Map(entries) => {
209
221
  let mut renamed = false;
210
222
  for (key, child) in entries.iter_mut() {
@@ -457,7 +469,7 @@ fn is_console_unsafe(ch: char) -> bool {
457
469
  | '\u{200E}'
458
470
  | '\u{200F}'
459
471
  | '\u{202A}'..='\u{202E}'
460
- | '\u{2066}'..='\u{2069}'
472
+ | '\u{2066}'..='\u{206F}'
461
473
  )
462
474
  }
463
475
 
@@ -584,6 +596,7 @@ fn display_value(value: &Value, buf: &mut String) {
584
596
  buf.push('}');
585
597
  }
586
598
  Value::Raw(json) => buf.push_str(json), // already-serialized; emit verbatim
599
+ Value::Keyed { value, .. } => display_value(value, buf),
587
600
  }
588
601
  }
589
602
 
@@ -1237,6 +1250,16 @@ mod tests {
1237
1250
  );
1238
1251
  }
1239
1252
 
1253
+ #[test]
1254
+ fn backtracking_evaluation_failure_redacts_through_render_pipeline() {
1255
+ let pattern = RedactionPattern::backtracking_with_limit(r"(a+)+\1$", 1).unwrap();
1256
+ let text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa!";
1257
+ assert_eq!(
1258
+ apply_patterns(text, &[pattern], "[X]"),
1259
+ Some(REDACTED.to_owned())
1260
+ );
1261
+ }
1262
+
1240
1263
  #[test]
1241
1264
  fn key_redaction_and_pattern_redaction_combine() {
1242
1265
  // Key-based redaction masks "token"; pattern-based masks the email in "msg".
@@ -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![