| 1 | import { closeSync, mkdirSync, openSync, renameSync, statSync, writeSync } from "node:fs"; |
| 2 | import { dirname } from "node:path"; |
| 3 | |
| 4 | export const LOG_ROTATE_BYTES = 5 * 1024 * 1024; |
| 5 | |
| 6 | export interface Logger { |
| 7 | info(message: string): void; |
| 8 | warn(message: string): void; |
| 9 | error(message: string): void; |
| 10 | } |
| 11 | |
| 12 | export class RotatingFile { |
| 13 | private fd: number | null = null; |
| 14 | private size = 0; |
| 15 | |
| 16 | constructor(readonly path: string, private readonly limit = LOG_ROTATE_BYTES) {} |
| 17 | |
| 18 | write(chunk: Buffer | string): void { |
| 19 | const data = typeof chunk === "string" ? Buffer.from(chunk) : chunk; |
| 20 | try { |
| 21 | if (this.fd === null) this.open(); |
| 22 | if (this.size + data.length > this.limit) this.rotate(); |
| 23 | writeSync(this.fd as number, data); |
| 24 | this.size += data.length; |
| 25 | } catch { |
| 26 | // Logging must never take the shell down. |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | close(): void { |
| 31 | if (this.fd === null) return; |
| 32 | try { |
| 33 | closeSync(this.fd); |
| 34 | } catch { |
| 35 | // Nothing to recover. |
| 36 | } |
| 37 | this.fd = null; |
| 38 | } |
| 39 | |
| 40 | private open(): void { |
| 41 | mkdirSync(dirname(this.path), { recursive: true }); |
| 42 | this.fd = openSync(this.path, "a"); |
| 43 | this.size = statSync(this.path).size; |
| 44 | } |
| 45 | |
| 46 | private rotate(): void { |
| 47 | this.close(); |
| 48 | renameSync(this.path, `${this.path}.1`); |
| 49 | this.open(); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | export function errorText(error: unknown): string { |
| 54 | if (error instanceof Error) return error.message; |
| 55 | if (typeof error === "string") return error; |
| 56 | try { |
| 57 | return JSON.stringify(error); |
| 58 | } catch { |
| 59 | return String(error); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | export function createLogger(file: RotatingFile, echo: boolean): Logger { |
| 64 | const emit = (level: string, message: string) => { |
| 65 | const line = `${new Date().toISOString()} ${level} ${message}\n`; |
| 66 | file.write(line); |
| 67 | if (echo) process.stderr.write(`[shell] ${line}`); |
| 68 | }; |
| 69 | return { |
| 70 | info: (message) => emit("info", message), |
| 71 | warn: (message) => emit("warn", message), |
| 72 | error: (message) => emit("error", message), |
| 73 | }; |
| 74 | } |
| 75 |