Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""A shared, tailable runtime log.
Every process — the worker and the servers — appends its log lines to onefile next to the store, so the admin site can show what is happening withoutreading the systemd journal. Each line still prints to stderr (where systemdcaptures it); this file is an extra, browsable copy. Bounded: once it growspast a cap the oldest lines are dropped. Leaf code — urllib-free, only thestore's directory is touched."""
import sysimport threadingimport timefrom pathlib import Path
ROOT = Path(__file__).parent.parentLOG_FILE = ROOT / "private" / "log.txt"MAX_BYTES = 1 << 20 # 1 MB of history before a trimKEEP_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:]