Skip to content

feat(logging): shared logger skeleton with Rule extension - #46

Merged
flying-sheep merged 25 commits into
scverse:mainfrom
timtreis:feat/shared-logger
Oct 26, 2026
Merged

flying-sheep merged 25 commits into
scverse:mainfrom
timtreis:feat/shared-logger

Conversation

@timtreis

@timtreis timtreis commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Shared logger for scverse packages. One scverse parent logger + single handler (rich if installed, else plain); package loggers are children, so verbosity/rich/rules are controlled centrally.

from scverse_misc.logging import get_logger, config, Rule

log = get_logger("spatialdata")        # real logging.Logger, child of "scverse"
config.verbosity = "info"              # central, all packages
config.add_rule(MyRule())              # 0..N rules

Sole extension point is Rule (keep/rewrite). Ships Elapsed/Deep universal rules (on by default, no-ops until used). get_logger(name, timed=True) opts into scanpy-style time=/deep=/.hint() + a datetime return.

Packages keep their behavior with a local rule

spatialdata-plot — report the public entry point instead of internal helpers:

from contextvars import ContextVar
_ctx: ContextVar[str] = ContextVar("ctx", default="")

class ContextPrefix(Rule):
    def rewrite(self, message, record):
        ctx = _ctx.get()
        return f"{ctx}: {message}" if ctx else message

config.add_rule(ContextPrefix())   # render_* entry points set _ctx

decoupler — always-on timestamp:

from datetime import datetime

class Timestamp(Rule):
    def rewrite(self, message, record):
        return f"{datetime.now():%H:%M:%S} | {message}"

config.add_rule(Timestamp())

design proposal for discussion

timtreis and others added 2 commits June 18, 2026 22:18
One `scverse` parent logger + single handler (rich auto-detected, else plain),
package loggers as children, central control via `config`. Sole extension point
is `Rule` (keep/rewrite); ships `Elapsed`/`Deep` universal rules on by default.
Opt-in `get_logger(name, timed=True)` adds scanpy-style `time=`/`deep=`/`.hint()`
and a datetime return.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@codecov

codecov Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.89041% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.29%. Comparing base (72b6fa6) to head (57af20a).

Files with missing lines Patch % Lines
src/scverse_misc/logging.py 96.55% 5 Missing ⚠️
src/scverse_misc/sphinx_ext/__init__.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #46      +/-   ##
==========================================
+ Coverage   93.81%   94.29%   +0.48%     
==========================================
  Files          12       13       +1     
  Lines         679      824     +145     
==========================================
+ Hits          637      777     +140     
- Misses         42       47       +5     
Files with missing lines Coverage Δ
src/scverse_misc/__init__.py 100.00% <ø> (ø)
src/scverse_misc/datasets/__init__.py 100.00% <ø> (ø)
src/scverse_misc/sphinx_ext/__init__.py 88.38% <0.00%> (ø)
src/scverse_misc/logging.py 96.55% <96.55%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

timtreis and others added 2 commits June 18, 2026 22:47
The logging module shipped its checks inside `if __name__ == "__main__"`,
which CI never runs, so the 255 new lines had 0% coverage; the same block
plus the module body also failed ruff (missing annotations/docstrings,
E702) and would fail strict mypy.

- annotate the public surface (`_emit`, level methods, `verbosity`,
  `get_logger` via @overload so `timed=True` narrows to `_TimedLogger`);
  add the missing `Rule` docstrings; type `_rules: list[Rule]`;
  `__getattr__ -> Any` for transparent delegation
- trim `_emit` to the documented `time=`/`deep=` surface (the old
  `**kwargs` passthrough never passed strict mypy)
- remove the `__main__` self-check, promote it to tests/test_logging.py
  (18 tests; logging.py coverage 0% -> 99%)

Verified locally: ruff check + format, mypy --strict, pytest all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
logging.py imports rich.logging lazily in the rich-handler branch. rich is
an optional runtime dep, but mypy needs it to resolve RichHandler (else
import-not-found + a no-any-return on the Handler return). Matches the
existing pattern of listing typecheck-only deps (pytest, sphinx) here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@timtreis
timtreis marked this pull request as ready for review June 18, 2026 20:52
Comment thread src/scverse_misc/logging.py Resolved
Comment thread src/scverse_misc/logging.py Resolved
Comment thread src/scverse_misc/logging.py Resolved
Comment thread src/scverse_misc/logging.py Resolved
timtreis and others added 6 commits June 19, 2026 13:47
- make TimedLogger public (returned from get_logger, meant to be subclassed)
- config.rich settable property for consistency with config.verbosity
- rename _Config._parent -> _root (it manages the scverse root logger)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Promote pydantic-settings + python-dotenv to hard dependencies (anndata
always pulls scverse-misc[settings] in anyway), and rebuild the logging
config on the shared Settings base instead of a bespoke _Config.

- verbosity/rich become validated Settings fields: env-var loading
  (SCVERSE_MISC_*), override/reset, and level validation come for free.
- rules stay bespoke (add_rule/remove_rule) — they aren't settings.
- _root/_rules derive from the live logger/handler, so there's no
  pydantic private-attr timing to manage and the test suite is unchanged.
- keep the (now empty) settings extra for anndata <0.13 back-compat.
- drop the dead suppress(ImportError) around Settings in __init__.

Addresses review feedback on scverse#46 (integrate logger with global config
handling; promote pydantic; rich settable).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/scverse_misc/logging.py Resolved
timtreis and others added 4 commits August 18, 2026 16:51
Address review feedback on scverse#46 (@flying-sheep): logging must not add hard
dependencies and must not depend on pydantic-settings.

- Drop anndata, pydantic-settings, python-dotenv from hard deps; restore the
  settings extra; anndata is now consumer-provided (kills the circular dep).
- logging config is two-tier via a shared _RuleAccess mixin + module helpers
  (_canonical_level, _reinstall, _add_rule/_remove_rule): full tier subclasses
  Settings (env-vars, override/reset) when pydantic-settings is present, else a
  stdlib reduced tier keeps verbosity/rich/rules. Single source of mechanics, so
  the tiers can't diverge.
- Re-guard the Settings export in __init__ with suppress(ImportError).
- Fix reduced-tier bugs surfaced by review: validate verbosity (no silent
  disable on bad int), rich defaults to None, _rules mirrors handler.filters
  (no resurrect on toggle), rich setter no-ops when unchanged.
- Guard tests/settings/* with importorskip(pydantic_settings); add a
  forced-fallback test; document the anndata loader requirement.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…view

Per @flying-sheep: logging must not pull pydantic-settings. Rest the
validated config tier on plain pydantic.BaseModel behind a new `logging`
extra; without pydantic the stdlib tier keeps identical behavior.

Also fold in review fixes clustered on the reviewers' themes:
- rich handler now logs to stderr (Console(stderr=True)), matching the
  plain handler and scanpy (grst's request)
- forcing config.rich=True without rich raises a clear ImportError
- tier parity: canonicalize the pydantic verbosity default and coerce
  rich to bool in the stdlib tier, so both tiers agree pre-assignment
- test group installs `rich` so the rich handler tier is exercised
- sink fixture restores rich + handler stream on teardown
- CHANGELOG: move datasets/logging entries to [Unreleased] (0.0.9 is
  released), fix typo

Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts:
#	pyproject.toml
#	tests/settings/test_sphinx.py
…amination

importlib.reload(mod) rebound the module's classes, so a later
isinstance(log, TimedLogger) compared against a stale class object and
failed (order/worker-dependent; tripped py3.12/3.13 under xdist). Load a
fresh, isolated module copy instead of reloading the shared one.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@timtreis
timtreis requested a review from flying-sheep August 18, 2026 19:16

@flying-sheep flying-sheep left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Regarding the design: I don’t like that rewrite actually changes the stored message – logging should separate context, message, and formatting.

E.g. people attaching a JSON log handler to decoupler’s logger should get {"message": ..., "extra": {"timestamp": ...}} or so (maybe flattened extra), not {"message": "2026-... | ..."}.

So I think this should be a two step process:

  1. add a hook that adds minimal data to extra. It should avoid any string wrangling and just do the absolute minimum to amend the data that’s stored (which also happens to be faster)
  2. configure the formatter for text logging to include the extra fields. We should use style="{" as nobody remembers how to use ancient C style formatting while we’re all using f-strings daily.

timtreis and others added 2 commits August 26, 2026 23:33
…records

Address review: filters no longer mutate `record.msg`. Context
(`time_passed`, `deep`) stays as record attributes; a single `_Extras`
filter derives render-ready `elapsed`/`detail` fields and a `{`-style
formatter on both handlers renders them. A JSON handler attached next
to ours now sees the raw message and args.

- drop `Rule`/`Elapsed`/`Deep` and the `rewrite` hook
- `config.add_rule`/`remove_rule` -> `add_filter`/`remove_filter`,
  accepting any `logging.Filter`
- inline `{time_passed}` placeholder removed (suffix only; scanpy's
  uses all render identically)

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RxgxHv7uTvnocVXymZsnTQ
@timtreis
timtreis requested a review from flying-sheep August 26, 2026 21:43
Comment thread src/scverse_misc/logging.py Resolved

@flying-sheep flying-sheep left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OK, made a few changes:

  1. no more gross Any, the logger is now actually typed
  2. removed LLM speek from the user-facing docstring
  3. fixed use of deprecated APIs
  4. made it so stuff gets formatted at formatting time, as I requested
obabo

@flying-sheep
flying-sheep merged commit 0687625 into scverse:main Oct 26, 2026
12 checks passed
@timtreis

Copy link
Copy Markdown
Member Author

Amazing, thanks for carrying it over the finish line and merging @flying-sheep !

@timtreis timtreis mentioned this pull request Nov 25, 2026
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.

4 participants