// PEP-291: a service's stdout/stderr also goes to $PEPPA_HOME/logs/.log, so the log // survives a redeploy (the container and its docker log are recreated on every rollout). import { closeSync, mkdirSync, openSync, readdirSync, renameSync, statSync, unlinkSync, writeSync, existsSync } from "node:fs"; import { join } from "node:path"; import { peppaHome } from "@peppa/shared"; export const SERVICE_LOG_DAYS = 7; export const SERVICE_LOG_MAX_MB = 200; export interface ServiceLogOptions { dir?: string; /** Rotated files whose day is older than this many days are removed. */ maxDays?: number; /** All files of the service together (the live one included). The live file rotates at a quarter. */ maxBytes?: number; now?: () => Date; } export function serviceLogDir(): string { return join(peppaHome(), "logs"); } export function serviceLogPath(service: string, dir = serviceLogDir()): string { return join(dir, `${service}.log`); } const day = (d: Date) => d.toISOString().slice(0, 10); const ROTATED_RE = /^\.(\d{4}-\d{2}-\d{2})(?:\.(\d+))?$/; export interface ServiceLogFile { name: string; path: string; size: number; /** null for the live file. */ day: string | null; n: number; } /** The live file and the rotated ones of a service, oldest rotated first, the live file last. */ export function serviceLogFiles(service: string, dir = serviceLogDir()): ServiceLogFile[] { let names: string[]; try { names = readdirSync(dir); } catch { return []; } const base = `${service}.log`; const out: ServiceLogFile[] = []; for (const name of names) { if (!name.startsWith(base)) continue; const rest = name.slice(base.length); const m = rest === "" ? null : ROTATED_RE.exec(rest); if (rest !== "" && !m) continue; let size = 0; try { size = statSync(join(dir, name)).size; } catch { continue; } out.push({ name, path: join(dir, name), size, day: m ? m[1]! : null, n: m?.[2] ? Number(m[2]) : 0 }); } return out.sort((a, b) => (a.day === null ? 1 : b.day === null ? -1 : a.day.localeCompare(b.day) || a.n - b.n)); } function envNumber(name: string, fallback: number): number { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; } /** An append-only file with daily and size rotation; writes are synchronous (order kept, nothing lost on a crash). */ export class RotatingLog { readonly service: string; readonly dir: string; readonly path: string; readonly maxDays: number; readonly maxBytes: number; private readonly now: () => Date; private fd: number | null = null; private size = 0; private day = ""; constructor(service: string, opts: ServiceLogOptions = {}) { this.service = service; this.dir = opts.dir ?? serviceLogDir(); this.path = serviceLogPath(service, this.dir); this.maxDays = opts.maxDays ?? envNumber("PEPPA_SERVICE_LOG_DAYS", SERVICE_LOG_DAYS); this.maxBytes = opts.maxBytes ?? envNumber("PEPPA_SERVICE_LOG_MAX_MB", SERVICE_LOG_MAX_MB) * 1024 * 1024; this.now = opts.now ?? (() => new Date()); } private get fileMax(): number { return Math.max(1, Math.floor(this.maxBytes / 4)); } private open(): void { mkdirSync(this.dir, { recursive: true }); if (existsSync(this.path)) { const st = statSync(this.path); this.size = st.size; this.day = day(st.mtime); } else { this.size = 0; this.day = day(this.now()); } this.fd = openSync(this.path, "a", 0o640); } write(chunk: string | Uint8Array): void { const buf = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); if (!buf.length) return; if (this.fd === null) this.open(); const today = day(this.now()); if (this.size > 0 && (today !== this.day || this.size + buf.length > this.fileMax)) this.rotate(); this.day = today; writeSync(this.fd!, buf); this.size += buf.length; } /** The live file goes to .log.[.N]; then old and excess files are removed. */ rotate(): void { if (this.fd !== null) closeSync(this.fd); this.fd = null; if (existsSync(this.path)) { let target = `${this.path}.${this.day}`; for (let n = 1; existsSync(target); n++) target = `${this.path}.${this.day}.${n}`; renameSync(this.path, target); } this.prune(); this.size = 0; this.day = day(this.now()); mkdirSync(this.dir, { recursive: true }); this.fd = openSync(this.path, "a", 0o640); } prune(): void { const cutoff = day(new Date(this.now().getTime() - this.maxDays * 86_400_000)); const files = serviceLogFiles(this.service, this.dir); const kept: ServiceLogFile[] = []; for (const f of files) { if (f.day !== null && f.day < cutoff) remove(f.path); else kept.push(f); } let total = kept.reduce((s, f) => s + f.size, 0); for (const f of kept) { if (total <= this.maxBytes) break; if (f.day === null) continue; remove(f.path); total -= f.size; } } close(): void { if (this.fd !== null) closeSync(this.fd); this.fd = null; } } function remove(path: string): void { try { unlinkSync(path); } catch { /* already gone */ } } type Write = typeof process.stdout.write; let installed: RotatingLog | null = null; /** * Tee the process's stdout and stderr into the service's rotating log file. Once per process; * `PEPPA_SERVICE_LOG=off` turns it off. A write failure turns the file off (one line to stderr), * the service keeps running. Returns the file path, or null when off. */ export function installServiceLog(service: string, opts: ServiceLogOptions = {}): string | null { if (installed) return installed.path; if (process.env.PEPPA_SERVICE_LOG === "off") return null; const log = new RotatingLog(service, opts); installed = log; let broken = false; const origErr = process.stderr.write.bind(process.stderr) as Write; const tee = (stream: NodeJS.WriteStream) => { const orig = stream.write.bind(stream) as Write; stream.write = ((chunk: string | Uint8Array, enc?: unknown, cb?: unknown) => { if (!broken) { try { log.write(typeof chunk === "string" && typeof enc === "string" && enc !== "utf8" && enc !== "utf-8" ? Buffer.from(chunk, enc as BufferEncoding) : chunk); } catch (e) { broken = true; try { log.close(); } catch { /* ignore */ } origErr(`service log ${log.path} is off: ${(e as Error).message}\n`); } } return (orig as (...a: unknown[]) => boolean)(chunk, enc, cb); }) as Write; }; tee(process.stdout); tee(process.stderr); return log.path; }