"""E22.5 S2 — every module's logger is named after the module. The names used to be literals, and 25 of them covered 34 modules: `plex/client.py`, `plex/stream.py`, `plex/subtitles.py`, `plex/sync.py` and two route modules all called themselves `siftlode.plex`, and `downloads/pipeline.py` called itself `siftlode.worker`. A level pinned per logger could not separate them, and neither can E22.6's console filter — the `logger` field is in every stored row precisely so it can be filtered on. So the name is derived, not written: `logs.get_logger(__name__)`. These cases pin the derivation and the rule, because the rule is only worth having if a hand-rolled name fails the gate. """ import ast import logging import pathlib import pytest from app import logs APP = pathlib.Path(logs.__file__).resolve().parent _ESCAPE = "logger-name-ok" @pytest.mark.parametrize( ("module", "expected"), [ ("app.plex.sync", "siftlode.plex.sync"), ("app.plex.stream", "siftlode.plex.stream"), ("app.routes.channels", "siftlode.routes.channels"), ("app.worker", "siftlode.worker"), # Not a module of ours (a script, a doctest): it lands on the root of our tree rather than # inventing `siftlode.__main__`, which nothing would think to filter on. ("__main__", "siftlode"), ], ) def test_the_name_follows_the_module(module, expected): assert logs.get_logger(module).name == expected def test_every_derived_logger_stays_under_the_one_tree(): """`configure_logging` hangs the level and the handler off the root, and the tests attach their sink to `siftlode` — a name outside that tree would be invisible to both.""" for module in ("app.main", "app.plex.sync", "app.routes.plex.people", "app"): assert logs.get_logger(module).name.startswith("siftlode") def test_the_module_logger_is_reachable_by_its_derived_name(): """Not a new logger object per call: the stdlib registry is keyed by name, and an operator pinning `siftlode.plex.sync` has to reach the same instance the module logs through.""" from app.plex import sync assert sync.log is logging.getLogger("siftlode.plex.sync") def test_no_module_hand_rolls_a_logger_name(): offenders = [] for path in sorted(APP.rglob("*.py")): src = path.read_text(encoding="utf-8") lines = src.splitlines() for node in ast.walk(ast.parse(src)): if not isinstance(node, ast.Call): continue func = node.func if not (isinstance(func, ast.Attribute) and func.attr == "getLogger"): continue # A no-argument `logging.getLogger()` is the ROOT logger — level plumbing, not a # module's own logger, and nothing to name. if not node.args: continue start = max(0, node.lineno - 2) # the call's lines, plus the one above it span = " ".join(lines[start : (node.end_lineno or node.lineno)]) if _ESCAPE in span: continue offenders.append(f"{path.relative_to(APP)}:{node.lineno}") assert offenders == [], ( "a module names its own logger; use `logs.get_logger(__name__)`, or say why the name is " f"not the module's with `# {_ESCAPE}: ` — {offenders}" )