Skip to content

Add logger to Python SDK#2746

Merged
nezaj merged 3 commits into
mainfrom
add-logger-to-python-sdk
Jun 9, 2026
Merged

Add logger to Python SDK#2746
nezaj merged 3 commits into
mainfrom
add-logger-to-python-sdk

Conversation

@nezaj

@nezaj nezaj commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Follow up to #2745, adds ability to add logger to Python SDK matching JS admin sdk behavior.

Also updates docs to include a note about the logger config

@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 266c1b7f-2b5e-4667-bfaa-3bc09ba8cd2e

📥 Commits

Reviewing files that changed from the base of the PR and between 5f0bb6c and d88aaa1.

📒 Files selected for processing (1)
  • client/packages/version/src/version.ts

📝 Walkthrough

Walkthrough

This PR adds structured logging support to the async Python client. A new Logger protocol allows callers to route realtime SSE connection and subscription messages through custom loggers via verbose=True and an optional logger parameter. The logger propagates from client initialization through streams, readers, writers, connections, and subscriptions, emitting debug/info/error entries at lifecycle and message-handling checkpoints.

Changes

Logging Infrastructure and Integration

Layer / File(s) Summary
Logger protocol and public export
client/packages/python/src/instantdb/_logger.py, client/packages/python/src/instantdb/__init__.py
Defines Logger protocol with debug, info, error methods. Provides make_logger(enabled, base) factory that conditionally binds calls to real or no-op implementations. Exports Logger from the package.
Client initialization and stream propagation
client/packages/python/src/instantdb/_async/client.py, client/packages/python/src/instantdb/_async/streams/__init__.py, client/packages/python/src/instantdb/_async/streams/reader.py, client/packages/python/src/instantdb/_async/streams/writer.py
AsyncInstant accepts verbose and logger parameters, creates _log via make_logger, and propagates it through AsyncStreams, readers, writers, and subscribe_query. Cloning preserves logging configuration.
Stream connection and message logging
client/packages/python/src/instantdb/_async/streams/_connection.py, client/packages/python/src/instantdb/_async/subscribe.py
Connection and subscription classes accept _Log and emit debug/info/error entries for lifecycle events: SSE open/close, outgoing send (with event id), incoming message (with payload), reconnect attempts (with attempt count and delay), and subscription errors.
Test coverage, docs, and version
client/packages/python/tests/test_logger.py, client/www/app/docs/init/page.md, client/www/app/docs/start-python/page.md, client/packages/version/src/version.ts
Tests validate make_logger gating, integration with subscription/connection/client, hot-path formatting avoidance, verbose control, and clone behavior. Documentation adds logger init option and a "Logging" section for Python usage. Version constant bumped.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant AsyncInstant
  participant AsyncStreams
  participant AsyncStreamReader
  participant AsyncStreamWriter
  Caller->>AsyncInstant: __init__(verbose=True, logger=custom)
  AsyncInstant->>AsyncInstant: _log = make_logger(verbose, logger)
  AsyncInstant->>AsyncStreams: __init__(log=_log)
  AsyncStreams->>AsyncStreamReader: __init__(log=_log)
  AsyncStreams->>AsyncStreamWriter: __init__(log=_log)
  AsyncInstant->>AsyncInstant: subscribe_query(log=_log)
Loading

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Possibly related PRs:

  • Suggested reviewers:

    • stopachka
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% 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
Title check ✅ Passed The title accurately and concisely describes the main change: adding a logger feature to the Python SDK.
Description check ✅ Passed The description is related to the changeset, explaining it as a follow-up to add logger functionality matching the JS SDK and updates documentation accordingly.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 add-logger-to-python-sdk

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.

@stopachka stopachka left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

sgtm!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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 `@client/packages/python/src/instantdb/_async/streams/_connection.py`:
- Line 158: The debug log lines currently force message stringification
(f"[send] {event_id} {msg}" and similar at the receive path) even when debug
logging is disabled; update the calls in _connection.py to avoid eager
formatting by either wrapping them with a debug-level guard (e.g., if
self._log.isEnabledFor(logging.DEBUG): self._log.debug(f"...")) or by using lazy
formatting via the logger's formatting API (e.g., self._log.debug("[send] %s
%s", event_id, msg)); apply the same change for the corresponding receive log at
the second occurrence so both hot-path send/receive avoid unnecessary
serialization.

In `@client/packages/python/src/instantdb/_async/subscribe.py`:
- Line 145: The debug calls in subscribe (e.g., the f-string at
self._log.debug(f"[receive] {msg}") and the similar one around line 187) eagerly
format strings even when debug is disabled; wrap those debug log calls in a
guard like if self._log.isEnabledFor(logging.DEBUG): ... or switch to logger
lazy formatting (pass format and args instead of an f-string) so the expensive
payload/error string formatting only happens when DEBUG is enabled; update the
occurrences at the debug calls (self._log.debug) in the subscribe/_async logic
accordingly.

In `@client/packages/python/tests/test_logger.py`:
- Around line 82-90: The test test_stream_connection_logs_received_messages
creates an _AsyncHTTP instance but never closes it, causing a client leak;
update the test to ensure the _AsyncHTTP created for _AsyncStreamConnection is
closed (use a try/finally or async context) — locate where _AsyncHTTP(...) is
constructed for _AsyncStreamConnection in the test, wrap the connection usage in
a try/finally and call await http_instance.aclose() (or the instance used in
_AsyncStreamConnection) in the finally so the HTTP client is properly closed
after conn._dispatch.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3ef1af57-5bdd-4db3-a33f-516b13dc9643

📥 Commits

Reviewing files that changed from the base of the PR and between 27a90e6 and 22b9b4f.

📒 Files selected for processing (11)
  • client/packages/python/src/instantdb/__init__.py
  • client/packages/python/src/instantdb/_async/client.py
  • client/packages/python/src/instantdb/_async/streams/__init__.py
  • client/packages/python/src/instantdb/_async/streams/_connection.py
  • client/packages/python/src/instantdb/_async/streams/reader.py
  • client/packages/python/src/instantdb/_async/streams/writer.py
  • client/packages/python/src/instantdb/_async/subscribe.py
  • client/packages/python/src/instantdb/_logger.py
  • client/packages/python/tests/test_logger.py
  • client/www/app/docs/init/page.md
  • client/www/app/docs/start-python/page.md

Comment thread client/packages/python/src/instantdb/_async/streams/_connection.py Outdated
Comment thread client/packages/python/src/instantdb/_async/subscribe.py Outdated
Comment thread client/packages/python/tests/test_logger.py Outdated
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

View Vercel preview at instant-www-js-add-logger-to-python-sdk-jsv.vercel.app.

- Skip building [send]/[receive] log strings when logging is disabled, so a
  verbose=False client never serializes message payloads on the hot path
- Close _AsyncHTTP in the stream-connection logger test
- Add a regression test that the disabled hot path skips payload formatting
- Drop redundant private-attribute asserts from the clone test

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@nezaj nezaj merged commit c3a5f48 into main Jun 9, 2026
6 of 7 checks passed
@nezaj nezaj deleted the add-logger-to-python-sdk branch June 9, 2026 14:29
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