"""A shared, tailable runtime log. Every process — the worker and the servers — appends its log lines to one file next to the store, so the admin site can show what is happening without reading the systemd journal. Each line still prints to stderr (where systemd captures it); this file is an extra, browsable copy. Bounded: once it grows past a cap the oldest lines are dropped. Leaf code — urllib-free, only the store's directory is touched. """ import sys import threading import time from pathlib import Path ROOT = Path(__file__).parent.parent LOG_FILE = ROOT / "private" / "log.txt" MAX_BYTES = 1 << 20 # 1 MB of history before a trim KEEP_LINES = 2000 # how much survives a trim _lock = threading.Lock() def log(*parts): """Append one log line to the shared file and print it to stderr. The format matches the servers' old inline log(): [HH:MM:SS] parts...""" line = f"[{time.strftime('%H:%M:%S')}] " + " ".join(str(p) for p in parts) with _lock: try: with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(line + "\n") if LOG_FILE.stat().st_size > MAX_BYTES: _trim() except OSError: pass print(line, file=sys.stderr, flush=True) def _trim(): try: lines = LOG_FILE.read_text(encoding="utf-8").splitlines()[-KEEP_LINES:] LOG_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8") except OSError: pass def tail(n: int = 200) -> list[str]: """The last `n` log lines, oldest first. Empty when nothing is logged yet or the file cannot be read.""" try: lines = LOG_FILE.read_text(encoding="utf-8").splitlines() except OSError: return [] return lines[-n:]