Platform v2 step 1.2 (APPS_PLATFORM D-12, §3.2, §8).
- core/errors.py: XeniaError + CODES registry; handlers give every error the
{"error": {code, params, message}, "detail"} shape: XeniaError, wrapped
HTTPException (http.<status>, detail untouched), validation.invalid (FastAPI
detail list kept), and internal.error 500 with the request id (body, header
and log line)
- orders: the 18 "Order not found" raises -> XeniaError("order.not_found")
- core/i18n: t(key, lang, **params) with en/el JSON (en fallback), venue/zone/
user language resolution, normalize_language; 56 print keys
- printer_service: every printed label goes through keys. Kitchen,
cancellation and service-item tickets print in the prep zone's language
(-> venue.language); reports/receipts/synopsis in venue.language. Greek
output is unchanged. Print retries now pass the job's zone (language and
item grouping were lost on retries)
- users.language, prep_zones.language (revision 0003), setting venue.language
(default en); editable via PATCH /auth/me, staff update, prep zones API;
"" = inherit
- tests: error shapes, key/placeholder parity, fallback, kitchen ticket per
zone/venue language, language APIs; pack rule CS-12
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
280 lines
11 KiB
Python
280 lines
11 KiB
Python
"""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
|
|
|
|
from core.timeutil import utcnow
|
|
|
|
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 utcnow()).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})
|
|
# Also on request.state: the last-resort error handler runs outside this middleware
|
|
scope.setdefault("state", {})["request_id"] = req_id
|
|
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)
|