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)
+18 -3
View File
@@ -1,10 +1,18 @@
import os
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from database import engine, Base
from core.logging import setup_logging, apply_retention_setting, RequestContextMiddleware
# First thing: every logger below (and uvicorn's) writes through these handlers.
setup_logging()
logger = logging.getLogger("xenia.main")
from config import settings
from database import engine, Base, SessionLocal
from middleware.license_check import LicenseCheckMiddleware
from services.cloud_sync import start_cloud_sync
@@ -771,14 +779,19 @@ async def lifespan(app: FastAPI):
ws_init_loop(loop)
Base.metadata.create_all(bind=engine)
_run_migrations()
_db = SessionLocal()
try:
apply_retention_setting(_db)
finally:
_db.close()
logger.info("startup version=%s", settings.VERSION)
# Before the app reports healthy: the proxy's :8443 needs these files to start
from services.tls_identity import ensure_tls_identity
ensure_tls_identity()
start_print_retry_thread()
pruned = prune_old_events(hours=24)
if pruned:
import logging
logging.getLogger(__name__).info("ws_bus: pruned %d old sync_events", pruned)
logger.info("ws_bus: pruned %d old sync_events", pruned)
_init_chat()
sync_task = await start_cloud_sync()
reservation_task = await start_reservation_tasks()
@@ -796,6 +809,8 @@ app.add_middleware(
allow_headers=["*"],
)
app.add_middleware(LicenseCheckMiddleware)
# Added last = outermost: the request id exists before any other middleware runs.
app.add_middleware(RequestContextMiddleware)
# Serve product images as static files
IMAGE_DIR = "/app/data/product_images"
+3
View File
@@ -7,6 +7,7 @@ from sqlalchemy.orm import Session
from database import get_db
from config import settings
from models.user import User
from core.logging import set_log_context
bearer = HTTPBearer()
@@ -86,10 +87,12 @@ def get_current_user(
) -> User:
payload = decode_token(credentials.credentials)
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
set_log_context(user="support")
return _make_ghost_superadmin()
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
set_log_context(user=user.id)
return user
+3
View File
@@ -1685,6 +1685,9 @@ def cancel_print_job(
item.printed = True
db.commit()
import logging
logging.getLogger("services.printer_service").warning(
"print.job.abandoned job=%s order=%s attempts=%s reason=staff_cancelled", pj.id, order_id, pj.retry_count)
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "print_job_cancelled"})
return {"ok": True, "job_id": job_id}
+2
View File
@@ -23,6 +23,7 @@ VALID_SETTINGS = {
"shifts.hide_revenue_from_waiters": "Hide ΕΙΣΠΡΑΞΗ and ΠΑΡΑΔ. ΠΟΣΟ stats from waiters in Shift Overview: 'true' | 'false'",
"business_day.force_close_allowed": "Allow force-closing business day with open tables",
"system.timezone": "IANA timezone name used by the backend container (e.g. Europe/Athens). Requires container restart to take effect.",
"system.log_retention_days": "Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.",
"ui.table_colours": "JSON blob of table card colour scheme (light + dark modes) for the Waiter PWA.",
"dev.spoof_printing": "When enabled, all print jobs are silently dropped. Devices behave as if printing succeeded.",
# Print layout
@@ -79,6 +80,7 @@ DEFAULTS = {
"shifts.hide_revenue_from_waiters": "false",
"business_day.force_close_allowed": "true",
"system.timezone": "Europe/Athens",
"system.log_retention_days": "30",
"ui.table_colours": '{"light":{"free":{"cardBg":"#dde5ef","badgeBg":"rgba(255,255,255,0.92)","nameText":"#3d5270","badgeText":"#3d5270"},"mine":{"cardBg":"#e8610a","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#e8610a"},"open":{"cardBg":"#FF8F60","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#FF8F60"},"partially_paid":{"cardBg":"#FFDC67","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#d4a800"},"paid":{"cardBg":"#81D264","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#81D264"},"kds_ready":{"cardBg":"#22c55e","cardBg2":"#ffffff","badgeBg":"rgba(255,255,255,0.92)","badgeBg2":"rgba(255,255,255,0.92)","nameText":"#ffffff","nameText2":"#15803d","badgeText":"#15803d","badgeText2":"#22c55e","flash":true}},"dark":{"free":{"cardBg":"#243044","badgeBg":"rgba(255,255,255,0.92)","nameText":"#94b8d4","badgeText":"#94b8d4"},"mine":{"cardBg":"#e8610a","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#e8610a"},"open":{"cardBg":"#FF8F60","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#FF8F60"},"partially_paid":{"cardBg":"#FFDC67","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#d4a800"},"paid":{"cardBg":"#81D264","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#81D264"},"kds_ready":{"cardBg":"#16a34a","cardBg2":"#ffffff","badgeBg":"rgba(255,255,255,0.92)","badgeBg2":"rgba(255,255,255,0.92)","nameText":"#ffffff","nameText2":"#bbf7d0","badgeText":"#bbf7d0","badgeText2":"#16a34a","flash":true}}}',
"dev.spoof_printing": "false",
"print.ticket_mode": "detailed",
-1
View File
@@ -26,7 +26,6 @@ from services.license import evaluate, parse_dt, verify_token
ORDER_POLL_INTERVAL = settings.CONNECT_SYNC_INTERVAL_SECONDS
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
SYNC_INTERVAL_SECONDS = 5 * 60 # 5 minutes
+18 -3
View File
@@ -1924,9 +1924,13 @@ def _do_route_and_print(order_id: int, item_ids: List[int], db: Session, ephemer
)
db.add(pj)
db.flush()
logger.info("print.job.created job=%s order=%s printer=%s zone=%s items=%s copies=%s",
pj.id, order_id, printer.name, zone_id or "-", item_ids_json, copies)
pj.last_attempted_at = now
pj.retry_count = (pj.retry_count or 0) + 1
logger.info("print.job.attempt job=%s attempt=%s printer=%s addr=%s:%s",
pj.id, pj.retry_count, printer.name, printer.ip_address, printer.port)
success = False
error_msg = None
@@ -1940,9 +1944,11 @@ def _do_route_and_print(order_id: int, item_ids: List[int], db: Session, ephemer
pj.succeeded_at = now
for item in job_items:
printed_item_ids.add(item.id)
logger.info("print.job.success job=%s attempt=%s printer=%s", pj.id, pj.retry_count, printer.name)
except Exception as e:
error_msg = str(e)
logger.error("Print failed for printer %s (%s:%s): %s", printer.name, printer.ip_address, printer.port, e)
logger.error("print.job.failed job=%s attempt=%s printer=%s addr=%s:%s will_retry=yes error=%r",
pj.id, pj.retry_count, printer.name, printer.ip_address, printer.port, error_msg)
log = PrintLog(
order_id=order_id,
@@ -2137,6 +2143,9 @@ def _retry_sweep():
pj.cancelled_at = now
pj.cancel_reason = "order_closed"
db.commit()
# The ticket never printed and never will: this is the job's final failure.
logger.warning("print.job.abandoned job=%s order=%s attempts=%s reason=order_closed",
pj.id, pj.order_id, pj.retry_count)
continue
item_ids = json.loads(pj.item_ids or "[]")
@@ -2151,14 +2160,19 @@ def _retry_sweep():
pj.status = "success"
pj.succeeded_at = now
db.commit()
logger.info("print.job.resolved job=%s reason=items_printed_or_removed", pj.id)
continue
printer = db.query(Printer).filter(Printer.id == pj.printer_id, Printer.is_active == True).first() # noqa: E712
if not printer:
logger.warning("print.job.skipped job=%s printer_id=%s reason=printer_missing_or_inactive",
pj.id, pj.printer_id)
continue
pj.last_attempted_at = now
pj.retry_count = (pj.retry_count or 0) + 1
logger.info("print.job.attempt job=%s attempt=%s printer=%s addr=%s:%s retry=yes",
pj.id, pj.retry_count, printer.name, printer.ip_address, printer.port)
success = False
error_msg = None
@@ -2172,10 +2186,11 @@ def _retry_sweep():
pj.succeeded_at = now
for item in active_unprinted:
item.printed = True
logger.info("PrintJob %s succeeded on retry %d", pj.id, pj.retry_count)
logger.info("print.job.success job=%s attempt=%s printer=%s retry=yes", pj.id, pj.retry_count, printer.name)
except Exception as e:
error_msg = str(e)
logger.warning("PrintJob %s retry %d failed: %s", pj.id, pj.retry_count, e)
logger.error("print.job.failed job=%s attempt=%s printer=%s addr=%s:%s will_retry=yes error=%r",
pj.id, pj.retry_count, printer.name, printer.ip_address, printer.port, error_msg)
db.add(PrintLog(
order_id=pj.order_id,
+107
View File
@@ -0,0 +1,107 @@
"""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) == ("-", "-", "-")