Skip to content

chore: add structured logging with secret redaction#277

Merged
mogita merged 3 commits into
mainfrom
feat/cha-2957-logging
Jul 22, 2026
Merged

chore: add structured logging with secret redaction#277
mogita merged 3 commits into
mainfrom
feat/cha-2957-logging

Conversation

@mogita

@mogita mogita commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Ticket

https://linear.app/stream/issue/CHA-2957/logging

Summary

Adds structured logging via a logger= kwarg (stdlib logging.Logger) on Stream/AsyncStream: client.initialized, http.request.sent, http.response.received, http.request.failed on both sync and async paths. Mandatory redaction of secret query params and known-secret body keys. Opt-in log_bodies with a one-shot WARN. No logger = no output (NullHandler).

Tests

Full unit suite green; tests/test_logging.py covers sync + async events, redaction, and the no-logger case.

Summary by CodeRabbit

  • New Features

    • Added optional structured logging for synchronous and asynchronous clients.
    • Added request, response, initialization, and transport-failure log events.
    • Added optional redacted request and response body logging.
    • Automatically redacts API secrets and sensitive fields; body logging is disabled by default.
    • Added support for supplying a custom logger when creating clients.
  • Documentation

    • Added logging configuration and event details to the README and changelog.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The SDK adds structured logging for client initialization and HTTP request lifecycles, configurable logger and body-logging options, redaction helpers, synchronous/asynchronous coverage, a package NullHandler, tests, and documentation.

Changes

Structured logging

Layer / File(s) Summary
Client logging configuration and initialization
getstream/__init__.py, getstream/stream.py, getstream/base.py, tests/test_http_client.py, CHANGELOG.md, README.md
Stream and AsyncStream accept logger and log_bodies, emit structured client.initialized events, propagate logging settings to cloned clients, and document the event schema and redaction behavior.
HTTP lifecycle events and redaction
getstream/logging_utils.py, getstream/base.py, tests/test_logging.py
Synchronous and asynchronous requests emit structured sent, received, and transport-failure events with redacted query parameters and optional redacted bodies; tests cover initialization, success, errors, disabled logging, redaction, warnings, and async behavior.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Stream
  participant _request_sync
  participant HTTPX
  participant Logger
  Stream->>_request_sync: configure logger and log_bodies
  _request_sync->>Logger: http.request.sent
  _request_sync->>HTTPX: send HTTP request
  HTTPX-->>_request_sync: response or RequestError
  _request_sync->>Logger: http.response.received or http.request.failed
Loading

Possibly related PRs

  • GetStream/stream-py#260: Updates the same client-construction logging paths that this change replaces with structured logging.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: structured logging with secret redaction.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cha-2957-logging

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
tests/test_logging.py (2)

10-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Use fixtures instead of helper factories and MockTransport.

Replace these helpers with pytest fixtures that inject the client and transport setup without mock objects.

As per coding guidelines, “Use fixtures to inject objects in tests” and “Do not use mocks or mock objects in tests unless directly requested.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_logging.py` around lines 10 - 31, Replace the make_client and
make_async_client helper factories in the logging tests with pytest fixtures
that provide the configured Stream and AsyncStream clients directly. Inject the
logger configuration and transport setup through fixtures, remove the
MockTransport-based mock objects, and update affected tests to consume the
fixtures.

Source: Coding guidelines


42-153: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Group the logging tests into test classes.

The synchronous and asynchronous logging scenarios are currently ungrouped module-level tests.

As per coding guidelines, “Keep tests well organized and use test classes to group similar tests.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_logging.py` around lines 42 - 153, Group the module-level logging
tests into appropriate test classes, separating synchronous scenarios from the
asynchronous scenario. Preserve each test’s existing name suffix, assertions,
fixtures, and behavior while nesting them under the new classes.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@getstream/__init__.py`:
- Line 15: Make the default getstream logger silent by setting its propagate
flag to false after installing the NullHandler in getstream/__init__.py. In
tests/test_http_client.py lines 418-485, attach the capture handler directly to
the getstream logger for intentional default-package event checks. In
tests/test_logging.py lines 91-97, assert that no getstream records are
captured, not merely that test.* records are absent.

In `@getstream/base.py`:
- Around line 94-100: Update the response-body handling around content_type so
media-type matching is case-insensitive and recognizes all JSON media types,
including structured types such as application/problem+json. Ensure every
recognized JSON response is parsed and passed through redact_json_body before
logging, while preserving the existing text fallback when parsing fails or the
response is not JSON.

In `@getstream/logging_utils.py`:
- Around line 5-6: Update the REDACTED_BODY_KEYS set to include api_key,
ensuring JSON request and response body logging redacts it consistently with the
existing REDACTED_QUERY_PARAMS behavior.

In `@tests/test_logging.py`:
- Around line 100-106: Update test_query_redaction to send a request containing
both a secret query parameter and a non-secret parameter. Assert the captured
http.request.sent record omits the secret value while retaining the non-secret
value, removing the empty-query fallback so the test exercises actual redaction.

---

Nitpick comments:
In `@tests/test_logging.py`:
- Around line 10-31: Replace the make_client and make_async_client helper
factories in the logging tests with pytest fixtures that provide the configured
Stream and AsyncStream clients directly. Inject the logger configuration and
transport setup through fixtures, remove the MockTransport-based mock objects,
and update affected tests to consume the fixtures.
- Around line 42-153: Group the module-level logging tests into appropriate test
classes, separating synchronous scenarios from the asynchronous scenario.
Preserve each test’s existing name suffix, assertions, fixtures, and behavior
while nesting them under the new classes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2ec2bdf2-988b-4121-bfe3-18501878828f

📥 Commits

Reviewing files that changed from the base of the PR and between 08747ad and 3c52708.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • README.md
  • getstream/__init__.py
  • getstream/base.py
  • getstream/logging_utils.py
  • getstream/stream.py
  • tests/test_http_client.py
  • tests/test_logging.py

Comment thread getstream/__init__.py
Comment thread getstream/base.py Outdated
Comment thread getstream/logging_utils.py
Comment thread tests/test_logging.py Outdated
@mogita

mogita commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Re the two nitpicks (pytest fixtures over helper factories + MockTransport; grouping tests into classes): httpx.MockTransport is httpx's standard first-class testing transport, not a unittest.mock object, so it fits the "no mock objects" guideline. Keeping this PR's diff focused on the logging feature; both are reasonable test-organization suggestions and can be picked up in a separate test-tidy pass. All four actionable comments are addressed in 4772f31.

@mogita mogita changed the title feat: add structured logging with secret redaction chore: add structured logging with secret redaction Jul 22, 2026
@mogita

mogita commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Titled chore: (not feat:) intentionally: this repo's Release workflow derives the version bump from the PR-title type and skips releasing when the type is not feat/fix, so merging this will not auto-publish. The change is a feature; when you want to publish, run the Release workflow manually (workflow_dispatch, version bump = minor).

@mogita
mogita merged commit 4bca6ba into main Jul 22, 2026
28 checks passed
@mogita
mogita deleted the feat/cha-2957-logging branch July 22, 2026 17:25
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.

1 participant