"""core/logging.py: request tagging, daily files, retention (plan step 0.4).""" import logging from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from core.logging import ( ContextFilter, DailyFileHandler, RequestContextMiddleware, UtcFormatter, _FORMAT, set_log_context, ) def _handler(tmp_path, days=30): h = DailyFileHandler(tmp_path, days) h.setFormatter(UtcFormatter(_FORMAT)) h.addFilter(ContextFilter()) return h def _record(msg, created=None): r = logging.LogRecord("t", logging.INFO, __file__, 1, msg, None, None) if created is not None: r.created = created r.msecs = 0 return r def test_file_named_by_utc_date_and_line_format(tmp_path): h = _handler(tmp_path) created = datetime(2026, 3, 29, 23, 30, tzinfo=timezone.utc).timestamp() # 02:30 Athens next day h.handle(_record("hello", created)) h.close() f = tmp_path / "xenia-2026-03-29.log" line = f.read_text(encoding="utf-8").strip() assert line.startswith("2026-03-29T23:30:00.000Z INFO t [req=- user=- device=-] hello") def test_switches_file_when_date_changes(tmp_path): h = _handler(tmp_path) d1 = datetime(2026, 11, 11, 23, 59, tzinfo=timezone.utc).timestamp() h.handle(_record("a", d1)) h.handle(_record("b", d1 + 120)) h.close() assert (tmp_path / "xenia-2026-11-11.log").read_text(encoding="utf-8").count("\n") == 1 assert (tmp_path / "xenia-2026-11-12.log").exists() def test_prune_keeps_retention_window(tmp_path): today = datetime(2026, 11, 12, tzinfo=timezone.utc) for back in (0, 5, 30, 31, 90): (tmp_path / f"xenia-{(today - timedelta(days=back)):%Y-%m-%d}.log").write_text("x") (tmp_path / "other.log").write_text("x") h = DailyFileHandler(tmp_path, retention_days=30) removed = {p.name for p in h.prune(today)} h.close() assert removed == {"xenia-2026-10-12.log", "xenia-2026-08-14.log"} assert (tmp_path / "other.log").exists() assert (tmp_path / "xenia-2026-10-13.log").exists() def _app_with_capture(): records = [] class Capture(logging.Handler): def emit(self, record): records.append(record) cap = Capture() cap.addFilter(ContextFilter()) lg = logging.getLogger("test.req") lg.addHandler(cap) lg.setLevel(logging.INFO) def fake_auth(): # sync dependency: runs in a worker thread with a copied context set_log_context(user=42) app = FastAPI() app.add_middleware(RequestContextMiddleware) @app.get("/x") def x(_=Depends(fake_auth)): # sync endpoint: another worker thread lg.info("inside") return {"ok": True} return app, records, lg, cap def test_request_id_header_and_tags_reach_endpoint_thread(): app, records, lg, cap = _app_with_capture() try: with TestClient(app) as c: r1 = c.get("/x") r2 = c.get("/x") finally: lg.removeHandler(cap) rid1, rid2 = r1.headers["x-request-id"], r2.headers["x-request-id"] assert rid1 and rid1 != rid2 inside = [r for r in records if r.getMessage() == "inside"] assert [r.req for r in inside] == [rid1, rid2] assert all(r.user == "42" for r in inside) def test_outside_request_tags_are_dashes(): r = _record("bg") ContextFilter().filter(r) assert (r.req, r.user, r.device) == ("-", "-", "-")