feat(backend): daily request-tagged log files + print job lifecycle logging

Platform v2 step 0.4 (APPS_PLATFORM §10). New core/logging.py:
- root logger -> stderr + <db dir>/logs/xenia-YYYY-MM-DD.log (UTC date,
  /app/data/logs in Docker, $LOG_DIR overrides); files older than the
  system.log_retention_days setting (default 30) are pruned
- line format: UTC ISO time, level, logger, [req= user= device=], message
- RequestContextMiddleware (pure ASGI): request id per request, X-Request-ID
  response header, one http line per request (DEBUG for plain reads)
- auth tags the user via set_log_context; uvicorn loggers routed through ours
Print jobs now log created / attempt / success / failed / abandoned with the
job id, so a missing ticket can be traced. Removed cloud_sync's basicConfig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 16:31:38 +02:00
co-authored by Claude Opus 5.5
parent e560d93cd5
commit 9fa728c039
9 changed files with 432 additions and 7 deletions
+6
View File
@@ -0,0 +1,6 @@
"""Platform v2 core: cross-cutting services every module uses (APPS_PLATFORM §10).
Agent note: things that belong here are shared by all modules and have no
business meaning of their own (logging, time, errors, access, module registry).
Feature code goes in its module, not here.
"""
+275
View File
@@ -0,0 +1,275 @@
"""Backend logging: one daily text file per UTC day, tagged with the request (APPS_PLATFORM §10).
Line format (human-readable, grep-friendly):
2026-11-12T10:39:25.226Z INFO services.printer_service [req=3f9a1c2e user=5 device=-] print.job.failed job=12 ...
Where files go:
<log dir>/xenia-YYYY-MM-DD.log (the date is the UTC date of the line)
log dir = $LOG_DIR, else "logs" next to the SQLite database
= /app/data/logs in Docker (DATABASE_URL=sqlite:////app/data/pos.db)
= %LOCALAPPDATA%\\pos\\logs in Windows dev
Files older than the retention (setting `system.log_retention_days`, default 30) are deleted.
How a line gets its tags:
RequestContextMiddleware puts a small mutable dict in a ContextVar for each
HTTP request. Auth code calls `set_log_context(user=...)`, which mutates that
dict. A mutable dict (not separate ContextVars) is used on purpose: FastAPI
runs sync dependencies and endpoints in worker threads with a *copy* of the
context, so a ContextVar.set() in a dependency would not be seen by the
endpoint, but a change to the shared dict is.
Lines from background threads (print retry, cloud sync) show req=-.
Agent notes:
- Call `setup_logging()` once, at import time of main.py, so uvicorn's own
loggers are re-pointed to our handlers (uvicorn configures logging before it
imports the app, so we run after it and win).
- Message style for new code: an event key first, then key=value pairs, e.g.
logger.info("print.job.created job=%s order=%s printer=%s", ...). That keeps
the file greppable by event.
- Never log secrets (tokens, PINs, passwords, license keys).
"""
from __future__ import annotations
import logging
import os
import re
import secrets
import sys
import time
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from pathlib import Path
DEFAULT_RETENTION_DAYS = 30
FILE_PREFIX = "xenia-"
_FILE_RE = re.compile(r"^xenia-(\d{4}-\d{2}-\d{2})\.log$")
_FORMAT = "%(asctime)s %(levelname)-5s %(name)s [req=%(req)s user=%(user)s device=%(device)s] %(message)s"
# The per-request context: {"req": str, "user": str|None, "device": str|None}
_ctx: ContextVar[dict | None] = ContextVar("xenia_log_ctx", default=None)
# ── context ──────────────────────────────────────────────────────────────────
def new_request_id() -> str:
return secrets.token_hex(4)
def set_log_context(**values) -> None:
"""Tag the current request's log lines, e.g. set_log_context(user=5).
No-op outside a request (background threads)."""
ctx = _ctx.get()
if ctx is not None:
for k, v in values.items():
ctx[k] = None if v is None else str(v)
def current_request_id() -> str | None:
ctx = _ctx.get()
return ctx["req"] if ctx else None
class ContextFilter(logging.Filter):
"""Adds req/user/device attributes to every record (\"-\" when unknown).
Attached to handlers, so records from every logger get them."""
def filter(self, record: logging.LogRecord) -> bool:
ctx = _ctx.get() or {}
record.req = ctx.get("req") or "-"
record.user = ctx.get("user") or "-"
record.device = ctx.get("device") or "-"
return True
class UtcFormatter(logging.Formatter):
"""ISO-8601 UTC timestamps with milliseconds and a Z."""
converter = time.gmtime
def formatTime(self, record, datefmt=None): # noqa: N802 (stdlib name)
dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{int(record.msecs):03d}Z"
# ── file handler ─────────────────────────────────────────────────────────────
class DailyFileHandler(logging.Handler):
"""Writes to <dir>/xenia-<UTC date>.log and switches file when the UTC date changes.
Why not TimedRotatingFileHandler: it writes to a fixed name and renames at
rollover, which gives `xenia.log.2026-11-12` names, and its rename fails on
Windows while another process has the file open. Opening a new dated file
needs no rename. Old files are pruned at each switch and at startup.
"""
def __init__(self, directory: Path, retention_days: int = DEFAULT_RETENTION_DAYS):
super().__init__()
self.directory = Path(directory)
self.directory.mkdir(parents=True, exist_ok=True)
self.retention_days = retention_days
self._date: str | None = None
self._stream = None
def path_for(self, date_str: str) -> Path:
return self.directory / f"{FILE_PREFIX}{date_str}.log"
def _open_for(self, date_str: str) -> None:
if self._stream:
self._stream.close()
self._stream = open(self.path_for(date_str), "a", encoding="utf-8")
self._date = date_str
self.prune()
def emit(self, record: logging.LogRecord) -> None:
try:
date_str = datetime.fromtimestamp(record.created, tz=timezone.utc).strftime("%Y-%m-%d")
if date_str != self._date:
self._open_for(date_str)
self._stream.write(self.format(record) + "\n")
self._stream.flush()
except Exception:
self.handleError(record)
def prune(self, today: datetime | None = None) -> list[Path]:
"""Delete files whose date is more than retention_days before today (UTC)."""
today = (today or datetime.now(timezone.utc)).date()
cutoff = today - timedelta(days=self.retention_days)
removed = []
for f in self.directory.glob(f"{FILE_PREFIX}*.log"):
m = _FILE_RE.match(f.name)
if not m:
continue
try:
if datetime.strptime(m.group(1), "%Y-%m-%d").date() < cutoff:
f.unlink()
removed.append(f)
except (ValueError, OSError):
continue
return removed
def close(self) -> None:
self.acquire()
try:
if self._stream:
self._stream.close()
self._stream = None
self._date = None
finally:
self.release()
super().close()
# ── setup ────────────────────────────────────────────────────────────────────
_file_handler: DailyFileHandler | None = None
def default_log_dir() -> Path:
if os.environ.get("LOG_DIR"):
return Path(os.environ["LOG_DIR"])
from config import settings
url = settings.DATABASE_URL
db_path = url.split("sqlite:///", 1)[1] if url.startswith("sqlite:///") else "./pos.db"
return Path(db_path).resolve().parent / "logs"
def setup_logging(log_dir: Path | None = None, level: int = logging.INFO,
retention_days: int = DEFAULT_RETENTION_DAYS) -> DailyFileHandler:
"""Configure the root logger: console (stderr) + daily file. Idempotent."""
global _file_handler
root = logging.getLogger()
for h in list(root.handlers):
if getattr(h, "_xenia", False):
root.removeHandler(h)
h.close()
fmt = UtcFormatter(_FORMAT)
ctx_filter = ContextFilter()
console = logging.StreamHandler(sys.stderr)
file_handler = DailyFileHandler(log_dir or default_log_dir(), retention_days)
for h in (console, file_handler):
h.setFormatter(fmt)
h.addFilter(ctx_filter)
h._xenia = True
root.addHandler(h)
root.setLevel(level)
# uvicorn installs its own handlers before importing the app. Send its
# server/error lines through ours; per-request lines come from our
# middleware instead of uvicorn.access (which has no request id).
for name in ("uvicorn", "uvicorn.error"):
lg = logging.getLogger(name)
lg.handlers.clear()
lg.propagate = True
access = logging.getLogger("uvicorn.access")
access.handlers.clear()
access.propagate = False
access.disabled = True
file_handler.prune()
_file_handler = file_handler
return file_handler
def apply_retention_setting(db) -> None:
"""Read `system.log_retention_days` from the settings table and prune. Called at startup."""
if _file_handler is None:
return
from models.settings import PosSettings
try:
row = db.query(PosSettings).filter(PosSettings.key == "system.log_retention_days").first()
days = int(row.value) if row and row.value else DEFAULT_RETENTION_DAYS
except Exception:
days = DEFAULT_RETENTION_DAYS
_file_handler.retention_days = max(1, days)
_file_handler.prune()
# ── request middleware ───────────────────────────────────────────────────────
_http_log = logging.getLogger("xenia.http")
_SLOW_MS = 1000
class RequestContextMiddleware:
"""Pure ASGI middleware: gives each HTTP/WebSocket request an id, puts it in
the log context and the `X-Request-ID` response header, and logs one line
per HTTP request (INFO for writes, errors and slow requests; DEBUG for
ordinary reads, so polling doesn't flood the file)."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket"):
return await self.app(scope, receive, send)
req_id = new_request_id()
token = _ctx.set({"req": req_id, "user": None, "device": None})
start = time.perf_counter()
status_holder = {"code": None}
async def send_wrapper(message):
if message["type"] == "http.response.start":
status_holder["code"] = message["status"]
headers = list(message.get("headers", []))
headers.append((b"x-request-id", req_id.encode()))
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, receive, send_wrapper)
except Exception:
_http_log.exception("http.unhandled %s %s", scope.get("method", "WS"), scope.get("path"))
raise
finally:
if scope["type"] == "http":
ms = int((time.perf_counter() - start) * 1000)
code = status_holder["code"]
method = scope.get("method", "")
lvl = logging.DEBUG
if method not in ("GET", "HEAD", "OPTIONS") or (code or 500) >= 400 or ms >= _SLOW_MS:
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
_ctx.reset(token)