structguru 1.7.1__tar.gz → 1.7.2__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.7.1 → structguru-1.7.2}/Cargo.lock +16 -16
  2. {structguru-1.7.1 → structguru-1.7.2}/Cargo.toml +7 -7
  3. {structguru-1.7.1 → structguru-1.7.2}/PKG-INFO +1 -1
  4. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/Cargo.toml +1 -1
  5. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/dispatch.rs +6 -0
  6. {structguru-1.7.1 → structguru-1.7.2}/pyproject.toml +13 -13
  7. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/__init__.py +1 -1
  8. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/_native_dispatch.py +2 -0
  9. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/_runtime.py +5 -9
  10. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/core.py +38 -47
  11. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/celery.py +7 -1
  12. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/flask.py +32 -30
  13. {structguru-1.7.1 → structguru-1.7.2}/LICENSE +0 -0
  14. {structguru-1.7.1 → structguru-1.7.2}/README.md +0 -0
  15. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/clock.rs +0 -0
  16. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/filter.rs +0 -0
  17. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/lib.rs +0 -0
  18. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/render.rs +0 -0
  19. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/value.rs +0 -0
  20. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-core/src/worker.rs +0 -0
  21. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/Cargo.toml +0 -0
  22. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/conversion.rs +0 -0
  23. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/exception.rs +0 -0
  24. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/filter.rs +0 -0
  25. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/lib.rs +0 -0
  26. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/local_repr.rs +0 -0
  27. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/pipeline.rs +0 -0
  28. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/rendering.rs +0 -0
  29. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/submission.rs +0 -0
  30. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/template.rs +0 -0
  31. {structguru-1.7.1 → structguru-1.7.2}/crates/structguru-py/src/writer.rs +0 -0
  32. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/_contextvars.py +0 -0
  33. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/_levels.py +0 -0
  34. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/_native_env.py +0 -0
  35. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/config.py +0 -0
  36. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/exceptions.py +0 -0
  37. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/__init__.py +0 -0
  38. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/_stdlib_env.py +0 -0
  39. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/_util.py +0 -0
  40. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/asgi.py +0 -0
  41. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/django.py +0 -0
  42. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/grpc.py +0 -0
  43. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/httpx.py +0 -0
  44. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/requests.py +0 -0
  45. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/sentry.py +0 -0
  46. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/sqlalchemy.py +0 -0
  47. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/integrations/stdlib.py +0 -0
  48. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/metrics.py +0 -0
  49. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/otel.py +0 -0
  50. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/py.typed +0 -0
  51. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/redaction.py +0 -0
  52. {structguru-1.7.1 → structguru-1.7.2}/src/structguru/settings.py +0 -0
@@ -34,9 +34,9 @@ checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
34
34
 
35
35
  [[package]]
36
36
  name = "fancy-regex"
37
- version = "0.20.0"
37
+ version = "0.20.2"
38
38
  source = "registry+https://github.com/rust-lang/crates.io-index"
39
- checksum = "20ed7f62ce0ae0da1a8b93c3c7104ab7e0760a74491e097c701fff966e945390"
39
+ checksum = "0a2e16b9a584b602f1e0e5e22c30ca0906786088c27500653e432d086def8b53"
40
40
  dependencies = [
41
41
  "bit-set",
42
42
  "regex-automata",
@@ -57,9 +57,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
57
57
 
58
58
  [[package]]
59
59
  name = "itoa"
60
- version = "1.0.18"
60
+ version = "1.0.19"
61
61
  source = "registry+https://github.com/rust-lang/crates.io-index"
62
- checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
62
+ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
63
63
 
64
64
  [[package]]
65
65
  name = "libc"
@@ -174,9 +174,9 @@ dependencies = [
174
174
 
175
175
  [[package]]
176
176
  name = "regex"
177
- version = "1.13.1"
177
+ version = "1.13.2"
178
178
  source = "registry+https://github.com/rust-lang/crates.io-index"
179
- checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
179
+ checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
180
180
  dependencies = [
181
181
  "aho-corasick",
182
182
  "memchr",
@@ -186,9 +186,9 @@ dependencies = [
186
186
 
187
187
  [[package]]
188
188
  name = "regex-automata"
189
- version = "0.4.18"
189
+ version = "0.4.19"
190
190
  source = "registry+https://github.com/rust-lang/crates.io-index"
191
- checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
191
+ checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
192
192
  dependencies = [
193
193
  "aho-corasick",
194
194
  "memchr",
@@ -197,9 +197,9 @@ dependencies = [
197
197
 
198
198
  [[package]]
199
199
  name = "regex-syntax"
200
- version = "0.8.11"
200
+ version = "0.8.12"
201
201
  source = "registry+https://github.com/rust-lang/crates.io-index"
202
- checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
202
+ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
203
203
 
204
204
  [[package]]
205
205
  name = "serde"
@@ -245,7 +245,7 @@ dependencies = [
245
245
 
246
246
  [[package]]
247
247
  name = "structguru-core"
248
- version = "1.7.1"
248
+ version = "1.7.2"
249
249
  dependencies = [
250
250
  "fancy-regex",
251
251
  "fastrand",
@@ -258,7 +258,7 @@ dependencies = [
258
258
 
259
259
  [[package]]
260
260
  name = "structguru-py"
261
- version = "1.7.1"
261
+ version = "1.7.2"
262
262
  dependencies = [
263
263
  "pyo3",
264
264
  "regex",
@@ -267,9 +267,9 @@ dependencies = [
267
267
 
268
268
  [[package]]
269
269
  name = "syn"
270
- version = "3.0.9"
270
+ version = "3.0.10"
271
271
  source = "registry+https://github.com/rust-lang/crates.io-index"
272
- checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
272
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
273
273
  dependencies = [
274
274
  "proc-macro2",
275
275
  "quote",
@@ -278,9 +278,9 @@ dependencies = [
278
278
 
279
279
  [[package]]
280
280
  name = "target-lexicon"
281
- version = "0.13.5"
281
+ version = "0.13.6"
282
282
  source = "registry+https://github.com/rust-lang/crates.io-index"
283
- checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
283
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
284
284
 
285
285
  [[package]]
286
286
  name = "time"
@@ -3,7 +3,7 @@ members = ["crates/structguru-core", "crates/structguru-py"]
3
3
  resolver = "2"
4
4
 
5
5
  [workspace.package]
6
- version = "1.7.1"
6
+ version = "1.7.2"
7
7
  edition = "2024"
8
8
  rust-version = "1.89"
9
9
  license = "MIT"
@@ -26,17 +26,17 @@ strip = true
26
26
 
27
27
  [workspace.dependencies]
28
28
  pyo3 = { version = "0.30.1" }
29
- serde = { version = "1.0" }
30
- serde_json = { version = "1.0", features = ["raw_value"] }
31
- time = { version = "0.3", features = ["macros", "formatting"] }
29
+ serde = { version = "1.0.229" }
30
+ serde_json = { version = "1.0.154", features = ["raw_value"] }
31
+ time = { version = "0.3.55", features = ["macros", "formatting"] }
32
32
  # `unicode` is on by default in the regex crate; keep it so character classes
33
33
  # match Python's `re` defaults (which are Unicode-aware on `str`).
34
- regex = { version = "1", default-features = false, features = ["std", "unicode"] }
34
+ regex = { version = "1.13.2", 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.20", default-features = false, features = ["std", "unicode"] }
37
+ fancy-regex = { version = "0.20.2", 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.
41
- fastrand = { version = "2.5" }
41
+ fastrand = { version = "2.5.0" }
42
42
  structguru-core = { path = "crates/structguru-core" }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: structguru
3
- Version: 1.7.1
3
+ Version: 1.7.2
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -22,4 +22,4 @@ fancy-regex.workspace = true
22
22
  fastrand.workspace = true
23
23
 
24
24
  [target.'cfg(unix)'.dependencies]
25
- libc = "0.2"
25
+ libc = "0.2.191"
@@ -1560,6 +1560,12 @@ impl CallableDispatcher {
1560
1560
  Ok(false)
1561
1561
  }
1562
1562
 
1563
+ /// Account for a synchronous root-relay failure inside its callback scope.
1564
+ fn note_raw_error(&self, py: Python<'_>, error: Bound<'_, pyo3::exceptions::PyBaseException>) {
1565
+ self.inner
1566
+ .note_error(py, &PyErr::from_value(error.into_any()));
1567
+ }
1568
+
1563
1569
  /// Return callable dispatch queue, drop, and error metrics.
1564
1570
  fn metrics<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
1565
1571
  let registry = self.inner.lock_registry();
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["maturin>=1.15.0,<2"]
2
+ requires = ["maturin>=1.16.0,<2"]
3
3
  build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "structguru"
7
- version = "1.7.1"
7
+ version = "1.7.2"
8
8
  description = "Native structured logging with a loguru-style Python API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -54,34 +54,34 @@ dev = [
54
54
  { include-group = "bench" },
55
55
  ]
56
56
  test = [
57
- "pytest>=9.1.1",
58
- "pytest-asyncio>=1.4.1",
57
+ "pytest>=9.2.0",
58
+ "pytest-asyncio>=1.5.0",
59
59
  "pytest-cov>=7.1.0",
60
- "pytest-httpserver>=1.2.0",
60
+ "pytest-httpserver>=1.2.1",
61
61
  # structlog + orjson are kept as test-only deps for the golden parity suite
62
62
  # (which compares native output against the standard structlog/orjson path).
63
63
  "structlog>=26.1.0",
64
64
  "orjson>=3.13.0",
65
65
  # fastapi drives the full-stack example smoke test (examples/full_stack_fastapi);
66
66
  # celery/sqlalchemy/httpx it also needs come from the integration extras.
67
- "fastapi>=0.162.0",
67
+ "fastapi>=0.163.2",
68
68
  ]
69
69
  lint = [
70
- "mypy>=2.4.0",
71
- "ruff>=0.17.3",
70
+ "mypy>=2.4.1",
71
+ "ruff>=0.17.5",
72
72
  ]
73
73
  docs = [
74
74
  "mkdocs>=1.6.1",
75
- "mkdocs-material>=9.8.0",
75
+ "mkdocs-material>=9.8.1",
76
76
  "mkdocstrings[python]>=1.0.8",
77
77
  ]
78
78
  bench = [
79
- "pytest-benchmark>=5.3.0",
80
- "loguru>=0.7.3",
79
+ "pytest-benchmark>=5.3.1",
80
+ "loguru>=0.8.0",
81
81
  ]
82
82
  free-threaded = [
83
- "pytest>=9.1.1",
84
- "pytest-benchmark>=5.3.0",
83
+ "pytest>=9.2.0",
84
+ "pytest-benchmark>=5.3.1",
85
85
  ]
86
86
  wheel-audit = [
87
87
  "abi3audit==0.0.26",
@@ -23,7 +23,7 @@ from structguru.otel import add_otel_context
23
23
  from structguru.redaction import DEFAULT_SENSITIVE_KEYS
24
24
  from structguru.settings import Settings
25
25
 
26
- __version__ = "1.7.1"
26
+ __version__ = "1.7.2"
27
27
 
28
28
  __all__ = [
29
29
  "DEFAULT_SENSITIVE_KEYS",
@@ -67,6 +67,8 @@ class CallableDispatcherProtocol(Protocol):
67
67
 
68
68
  def enqueue(self, line: str, level: int, *, overflow: str) -> bool: ...
69
69
 
70
+ def note_raw_error(self, error: BaseException) -> None: ...
71
+
70
72
  def metrics(self) -> dict[str, int]: ...
71
73
 
72
74
  def reset_drop_count(self) -> None: ...
@@ -413,7 +413,6 @@ def notify_metrics(
413
413
  def notify_sentry(
414
414
  method: str,
415
415
  redacted_line: str,
416
- field_names: tuple[str, ...],
417
416
  exc_info: Any = None,
418
417
  runtime: _RuntimeState | None = None,
419
418
  ) -> None:
@@ -433,12 +432,11 @@ def notify_sentry(
433
432
  rendered = json.loads(redacted_line)
434
433
  except (json.JSONDecodeError, TypeError):
435
434
  return
436
- event_dict: dict[str, Any] = {"event": rendered.get("message", "")}
437
- for key in (*field_names, "service", "logger", "level", "severity", "timestamp"):
438
- # "event" is the hook's message slot. A user field by that name renders
439
- # natively as a field but must not replace the message exported here.
440
- if key != "event" and key in rendered:
441
- event_dict[key] = rendered[key]
435
+ # Reuse the sanitized record, including renderer-added and renamed keys.
436
+ # Only the exception control below may supply exc_info to a processor.
437
+ event_dict: dict[str, Any] = rendered
438
+ event_dict["event"] = event_dict.pop("message", "")
439
+ event_dict.pop("exc_info", None)
442
440
  from structguru.redaction import REDACTED_MARKER_KEY
443
441
 
444
442
  event_dict[REDACTED_MARKER_KEY] = True
@@ -1082,7 +1080,6 @@ def render_and_enqueue(
1082
1080
  stack: str | None,
1083
1081
  created: float | None = None,
1084
1082
  levelno: int | None = None,
1085
- field_names: tuple[str, ...] = (),
1086
1083
  exc_info: Any = None,
1087
1084
  ) -> None:
1088
1085
  """Merge, render, and submit one record to every configured destination.
@@ -1160,7 +1157,6 @@ def render_and_enqueue(
1160
1157
  notify_sentry(
1161
1158
  level,
1162
1159
  sentry_line,
1163
- field_names,
1164
1160
  exc_info=exc_info,
1165
1161
  runtime=runtime,
1166
1162
  )
@@ -78,11 +78,7 @@ class _CallableHandler(logging.Handler):
78
78
  self._fn = fn
79
79
 
80
80
  def emit(self, record: logging.LogRecord) -> None:
81
- try:
82
- msg = self.format(record)
83
- self._fn(msg)
84
- except Exception:
85
- self.handleError(record)
81
+ self._fn(self.format(record))
86
82
 
87
83
 
88
84
  class _SecureFileHandler(logging.FileHandler):
@@ -259,6 +255,28 @@ class _RedactingFormatter(string.Formatter):
259
255
  super().__init__()
260
256
  self._sensitive = sensitive
261
257
 
258
+ if sys.version_info < (3, 14):
259
+ # Older string.Formatter versions only auto-number a completely empty
260
+ # field. str.format also numbers the implicit root of "{[key]}".
261
+ _auto_index: int | None = 0
262
+
263
+ def parse(
264
+ self, format_string: str
265
+ ) -> Iterator[tuple[str, str | None, str | None, str | None]]:
266
+ for literal, field_name, spec, conversion in super().parse(format_string):
267
+ if field_name is not None:
268
+ root, _ = _field_path(field_name)
269
+ if not root:
270
+ if self._auto_index is None:
271
+ raise ValueError("cannot mix automatic and manual field numbering")
272
+ field_name = str(self._auto_index) + field_name
273
+ self._auto_index += 1
274
+ elif root.isdecimal():
275
+ if self._auto_index:
276
+ raise ValueError("cannot mix automatic and manual field numbering")
277
+ self._auto_index = None
278
+ yield literal, field_name, spec, conversion
279
+
262
280
  def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any:
263
281
  root, path = _field_path(field_name)
264
282
  if any(name.lower() in self._sensitive for name in (root, *path)):
@@ -283,35 +301,6 @@ class _RedactingFormatter(string.Formatter):
283
301
  return super().convert_field(value, conversion)
284
302
 
285
303
 
286
- def _may_expose_nested_secret(
287
- text: str,
288
- args: tuple[Any, ...],
289
- kwargs: dict[str, Any],
290
- consumed: frozenset[str],
291
- has_path: bool,
292
- sensitive: frozenset[str],
293
- ) -> bool:
294
- """True when plain formatting may have exposed a value under a sensitive key.
295
-
296
- Only a non-scalar argument, or an object reached by attribute or index,
297
- can carry a nested key, and its text then names that key. Scalar-only
298
- calls cost one type lookup per argument; the text is scanned only after.
299
- """
300
- if not has_path:
301
- for value in args:
302
- if type(value) not in _SCALAR_TYPES:
303
- break
304
- else:
305
- for name in consumed:
306
- if type(kwargs.get(name)) not in _SCALAR_TYPES:
307
- break
308
- else:
309
- return False
310
- # A case-insensitive regex alternation is several times slower than this.
311
- lowered = text.lower()
312
- return any(key in lowered for key in sensitive)
313
-
314
-
315
304
  def _safe_format(
316
305
  message: Any,
317
306
  args: tuple[Any, ...],
@@ -364,15 +353,16 @@ def _safe_format(
364
353
  consumed, names, names_default_key, has_path = template
365
354
  try:
366
355
  redact = names_default_key if keys is None else not names.isdisjoint(sensitive)
367
- if not redact:
368
- text = msg.format(*args, **kwargs)
369
- if not sensitive or not _may_expose_nested_secret(
370
- text, args, kwargs, consumed, has_path, sensitive
371
- ):
372
- return text, consumed
373
- # The pure-Python formatter is several times slower than str.format,
374
- # so it only re-renders a template whose plain text could hold a secret.
375
- return _RedactingFormatter(sensitive).vformat(msg, args, kwargs), consumed
356
+ # Container keys can be escaped or aliased in repr. Choose the structural
357
+ # formatter before rendering any argument, using only its type and path.
358
+ if sensitive and (
359
+ redact
360
+ or has_path
361
+ or any(type(value) not in _SCALAR_TYPES for value in args)
362
+ or any(type(kwargs.get(name)) not in _SCALAR_TYPES for name in consumed)
363
+ ):
364
+ return _RedactingFormatter(sensitive).vformat(msg, args, kwargs), consumed
365
+ return msg.format(*args, **kwargs), consumed
376
366
  except Exception as exc: # noqa: BLE001 - user __format__/__str__ may raise anything
377
367
  # Template/arg mismatch or a failing argument conversion from user
378
368
  # code (missing key, bad attribute, raising __format__, etc.).
@@ -422,7 +412,11 @@ class _RootRelay(logging.Handler):
422
412
  self._active += 1
423
413
  try:
424
414
  with callback_scope():
425
- return bool(self._sink.handle(record))
415
+ try:
416
+ return bool(self._sink.handle(record))
417
+ except BaseException as exc:
418
+ _runtime._callable_dispatcher.note_raw_error(exc)
419
+ return False
426
420
  finally:
427
421
  with self._condition:
428
422
  self._active -= 1
@@ -988,7 +982,6 @@ class Logger:
988
982
  # structlog's merge_contextvars setdefault semantics; the writer merges.
989
983
  bound = self._bound if _bound_fields is None else _bound_fields
990
984
  contextvars = _ctx.get()
991
- field_names: tuple[str, ...] = ()
992
985
  if runtime.enrich:
993
986
  fields = _runtime.merge_fields(bound, kwargs, contextvars)
994
987
  if runtime.otel:
@@ -996,7 +989,6 @@ class Logger:
996
989
  if exception is not None:
997
990
  fields["exception"] = exception
998
991
  _runtime.notify_metrics(method, formatted_msg, fields, runtime)
999
- field_names = tuple(fields)
1000
992
  bound, kwargs, contextvars, exception = fields, _NO_FIELDS, _NO_FIELDS, None
1001
993
  _runtime.render_and_enqueue(
1002
994
  runtime,
@@ -1010,7 +1002,6 @@ class Logger:
1010
1002
  stack,
1011
1003
  created,
1012
1004
  level_number,
1013
- field_names,
1014
1005
  exc_info,
1015
1006
  )
1016
1007
 
@@ -304,7 +304,13 @@ def setup_celery_logging(
304
304
  if isinstance(headers, dict):
305
305
  ctx = headers.get(_HEADER_KEY)
306
306
  if isinstance(ctx, dict):
307
- bind_contextvars(**{k: v for k, v in ctx.items() if isinstance(k, str)})
307
+ bind_contextvars(
308
+ **{
309
+ k: v
310
+ for k, v in ctx.items()
311
+ if isinstance(k, str) and (selected_keys is None or k in selected_keys)
312
+ }
313
+ )
308
314
 
309
315
  # A producer may itself be a task. Its propagated identity must never
310
316
  # replace the consumer's identity; correlation fields still propagate.
@@ -18,7 +18,12 @@ from typing import Any
18
18
 
19
19
  from structguru._contextvars import bind_contextvars, clear_contextvars, get_contextvars
20
20
  from structguru.core import Logger
21
- from structguru.integrations._util import ContextBoundIterator, StreamState, coerce_request_id
21
+ from structguru.integrations._util import (
22
+ ContextBoundIterator,
23
+ StreamState,
24
+ coerce_request_id,
25
+ replace_contextvars,
26
+ )
22
27
 
23
28
 
24
29
  def setup_flask_logging(
@@ -46,8 +51,8 @@ def setup_flask_logging(
46
51
  The binding hook runs before every other application ``before_request``
47
52
  hook, including ones registered earlier, so a hook that ends the request
48
53
  early (an authentication 401) still gets a request ID, a response header,
49
- and a summary line, and context those hooks bind is kept. The context is
50
- cleared after every other application ``teardown_request`` hook has run.
54
+ and a summary line, and context those hooks bind is kept. The enclosing context is
55
+ restored after every other application ``teardown_request`` hook has run.
51
56
 
52
57
  A streamed response body (a generator, with or without
53
58
  ``flask.stream_with_context``) is produced with the request context
@@ -67,13 +72,11 @@ def setup_flask_logging(
67
72
  log = Logger(name=logger_name)
68
73
 
69
74
  def _bind_request_context() -> None:
70
- from flask import g, request
71
-
72
- clear_contextvars()
75
+ from flask import request
73
76
 
74
77
  request_id = coerce_request_id(request.headers.get(request_id_header, ""))
75
- g.structguru_summary = _Summary(time.perf_counter())
76
- g.structguru_request_id = request_id
78
+ request.environ["structguru.summary"] = _Summary(request_id, get_contextvars())
79
+ clear_contextvars()
77
80
 
78
81
  bind_contextvars(
79
82
  request_id=request_id,
@@ -101,9 +104,9 @@ def setup_flask_logging(
101
104
  _log_summary(log, summary.start_time, status_code, None)
102
105
 
103
106
  def _on_request_finished(sender: Any, response: Any, **extra: Any) -> None:
104
- from flask import g
107
+ from flask import request
105
108
 
106
- summary: _Summary | None = getattr(g, "structguru_summary", None)
109
+ summary: _Summary | None = request.environ.get("structguru.summary")
107
110
  if summary is not None:
108
111
  _finalize(summary, response.status_code)
109
112
 
@@ -120,14 +123,14 @@ def setup_flask_logging(
120
123
 
121
124
  @app.after_request # type: ignore[untyped-decorator]
122
125
  def _log_response(response: Any) -> Any:
123
- from flask import g
126
+ from flask import request
124
127
  from werkzeug.wsgi import ClosingIterator
125
128
 
126
- request_id = getattr(g, "structguru_request_id", None)
127
- if request_id:
128
- response.headers[request_id_header] = request_id
129
- summary: _Summary | None = getattr(g, "structguru_summary", None)
130
- if summary is None or summary.finished:
129
+ summary: _Summary | None = request.environ.get("structguru.summary")
130
+ if summary is None:
131
+ return response
132
+ response.headers[request_id_header] = summary.request_id
133
+ if summary.finished:
131
134
  return response
132
135
  # When a later after_request hook fails, Flask processes a 500 response
133
136
  # instead and runs this hook again: the new response supersedes this
@@ -161,11 +164,14 @@ def setup_flask_logging(
161
164
  return response
162
165
 
163
166
  def _clear_context(exc: BaseException | None = None) -> None:
164
- from flask import g
167
+ from flask import request
165
168
 
169
+ # Flask can tear down a preserved or streamed request more than once.
170
+ summary: _Summary | None = request.environ.pop("structguru.summary", None)
171
+ if summary is None:
172
+ return
166
173
  try:
167
- summary: _Summary | None = getattr(g, "structguru_summary", None)
168
- if summary is not None and not summary.finished and not summary.logged:
174
+ if not summary.finished and not summary.logged:
169
175
  # No response was finalized: the exception propagated past
170
176
  # Flask (PROPAGATE_EXCEPTIONS, testing, debug) and the server
171
177
  # answers, or finalizing the error response failed too.
@@ -173,7 +179,7 @@ def setup_flask_logging(
173
179
  if log_request:
174
180
  _log_summary(log, summary.start_time, 500 if exc is not None else None, exc)
175
181
  finally:
176
- clear_contextvars()
182
+ replace_contextvars(summary.outer_context)
177
183
 
178
184
  # Teardown hooks run in reverse registration order: at the front of the
179
185
  # list, the clearing hook runs after every other application teardown hook,
@@ -185,18 +191,14 @@ def setup_flask_logging(
185
191
 
186
192
 
187
193
  class _Summary:
188
- """Per-request summary state: exactly one summary line per request.
189
-
190
- Parameters
191
- ----------
192
- start_time:
193
- ``time.perf_counter()`` value taken when the request started.
194
- """
194
+ """State owned by one request until its final response and teardown."""
195
195
 
196
- __slots__ = ("finished", "logged", "start_time", "stream")
196
+ __slots__ = ("finished", "logged", "outer_context", "request_id", "start_time", "stream")
197
197
 
198
- def __init__(self, start_time: float) -> None:
199
- self.start_time = start_time
198
+ def __init__(self, request_id: str, outer_context: dict[str, Any]) -> None:
199
+ self.start_time = time.perf_counter()
200
+ self.request_id = request_id
201
+ self.outer_context = outer_context
200
202
  #: The current response's streamed body, which logs its own summary.
201
203
  self.stream: StreamState | None = None
202
204
  #: Flask finalized a response (``request_finished`` or its fallback).
File without changes
File without changes