Skip to content

Conversation

paytoniga
Copy link
Collaborator

@paytoniga paytoniga commented Oct 2, 2025

Summary by CodeRabbit

  • New Features
    • None
  • Bug Fixes
    • Prevents accidental overwriting of log context, preserving per-request details.
    • Reduces noisy or duplicate fields in JSON logs for clearer output.
  • Refactor
    • Simplified and standardized how log context is merged across records.
    • Introduced consistent exclusions for non-essential record attributes.
    • Removed an obsolete standalone execution path.
  • Chores
    • Minor formatting and logical cleanups to align with updated logging behavior.

Copy link

coderabbitai bot commented Oct 2, 2025

Walkthrough

Refactors logging context handling in services/logging_config.py by simplifying JsonFormatter attribute merging via an excluded set, changing RequestLoggerAdapter extra/context merge to preserve existing keys, updating get/set context access patterns, removing a main-guarded setup block, and making minor formatting/logic tweaks.

Changes

Cohort / File(s) Summary
Logging context and formatting updates
services/logging_config.py
Simplified JsonFormatter.format: use base.update with _log_context.get(), introduce excluded set for record attribute merge; removed inline exclusion list. RequestLoggerAdapter.process now merges kwargs["extra"], adapter extras, and per-request context without overwriting existing keys. get/set context now omit default dicts. Removed main setup block.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Application Code
  participant Adp as RequestLoggerAdapter.process
  participant Log as Logger/Handler
  participant Fmt as JsonFormatter.format
  participant Sink as Output (e.g., stdout)

  App->>Adp: logger.info(msg, extra=...)
  note right of Adp: Merge order (no overwrite):<br/>1) kwargs["extra"]<br/>2) adapter extras<br/>3) per-request context (_log_context.get())
  Adp->>Log: emits LogRecord
  Log->>Fmt: format(record)
  note right of Fmt: base.update(_log_context.get())<br/>Record attrs merged excluding named set
  Fmt-->>Log: JSON string
  Log-->>Sink: write
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I twitch my ears at logs so bright,
Context hops in, merged just right.
No keys erased, exclusions neat—
Carrots counted, tidy feat.
With JSON trails my burrow sings,
A quieter thump of logging things. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the core change by indicating a refactor of the logging configuration with a focus on streamlining JSON formatting, which directly reflects the modifications made in services/logging_config.py.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/logs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8ad998 and 6388ea9.

📒 Files selected for processing (1)
  • services/logging_config.py (3 hunks)

Comment on lines +131 to 134
extra: Dict[str, Any] = kwargs.setdefault("extra", {})
extra.update({k: v for k, v in self.extra.items() if k not in extra})
extra.update({k: v for k, v in _log_context.get().items() if k not in extra})
return msg, kwargs
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid mutating caller-supplied extra
Line [131] grabs kwargs["extra"] and updates it in place, so any dict the caller passes (or reuses) now comes back polluted with adapter/context entries. That’s a behavioral regression: reuse of the same extra dict across log calls will leak stale request context into later logs, and even within the same call the caller sees unexpected mutations. Please copy the provided mapping before merging:

-        extra: Dict[str, Any] = kwargs.setdefault("extra", {})
-        extra.update({k: v for k, v in self.extra.items() if k not in extra})
-        extra.update({k: v for k, v in _log_context.get().items() if k not in extra})
+        provided_extra = kwargs.get("extra") or {}
+        extra: Dict[str, Any] = dict(provided_extra)
+        for k, v in self.extra.items():
+            extra.setdefault(k, v)
+        for k, v in _log_context.get().items():
+            extra.setdefault(k, v)
+        kwargs["extra"] = extra
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
extra: Dict[str, Any] = kwargs.setdefault("extra", {})
extra.update({k: v for k, v in self.extra.items() if k not in extra})
extra.update({k: v for k, v in _log_context.get().items() if k not in extra})
return msg, kwargs
provided_extra = kwargs.get("extra") or {}
extra: Dict[str, Any] = dict(provided_extra)
for k, v in self.extra.items():
extra.setdefault(k, v)
for k, v in _log_context.get().items():
extra.setdefault(k, v)
kwargs["extra"] = extra
return msg, kwargs
🤖 Prompt for AI Agents
In services/logging_config.py around lines 131 to 134, the code mutates the
caller-supplied kwargs["extra"] in place which leaks adapter/context entries
into caller-owned dicts; instead create a fresh dict by copying the provided
mapping (e.g. new_extra = dict(kwargs.get("extra", {})) or use
dict(kwargs["extra"]) if present), update that new dict with self.extra and
_log_context entries, and assign it back to kwargs["extra"] so the original
caller dict is not modified.

@fehranbit fehranbit merged commit 13271c6 into main Oct 2, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants