All files / src error-journal.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 5/5
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44        6x 6x       20x         485x 485x     20x         86x       235x           235x 235x 235x       235x 14x      
import { node } from "./binary-manager";
import { LOG_FILE, type JournalEntry } from "./types";
import { appendCapped } from "./utils/capped-log";
 
export const JOURNAL_MAX_ENTRIES = 200;
export const PLUGIN_LOG_MAX_BYTES = 262_144;
 
/** One journal entry as a log line (no trailing newline). */
export function formatJournalEntry(entry: JournalEntry): string {
    return `${entry.timestamp} [${entry.label}] ${entry.message}${entry.stack ? `\n${entry.stack}` : ""}`;
}
 
/** In-memory ring buffer of plugin errors, mirrored best-effort to logs/plugin.log. */
export class ErrorJournal {
    private _entries: JournalEntry[] = [];
    private logPath: string | null = null;
 
    get entries(): readonly JournalEntry[] {
        return this._entries;
    }
 
    /** Point persistence at `<dataDir>/logs`. */
    setLogDir(dir: string): void {
        this.logPath = node.join(dir, LOG_FILE.PLUGIN);
    }
 
    record(label: string, message: string, stack?: string): void {
        const entry: JournalEntry = {
            timestamp: new Date().toISOString(),
            label,
            message,
            stack: stack ?? null,
        };
        this._entries.push(entry);
        if (this._entries.length > JOURNAL_MAX_ENTRIES) this._entries.shift();
        this.append(entry);
    }
 
    private append(entry: JournalEntry): void {
        if (!this.logPath) return;
        appendCapped(this.logPath, `${formatJournalEntry(entry)}\n`, PLUGIN_LOG_MAX_BYTES);
    }
}