diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/core/src/utils/log-file-transport.ts index 211a126d..0b5b6d8c 100644 --- a/packages/core/src/utils/log-file-transport.ts +++ b/packages/core/src/utils/log-file-transport.ts @@ -1,16 +1,20 @@ // File transport for the SnowLuma logger. // // Writes plain text (ANSI stripped) to: -// /snowluma-YYYY-MM-DD.log -// with daily rollover and a per-file size cap. When the cap is hit the -// in-flight file is closed and writes continue in +// /snowluma-YYYY-MM-DD.log (shared, all UINs) +// //snowluma-YYYY-MM-DD.log (per-account) +// +// Both pathways use the same daily rotation + per-file size cap. When the +// cap is hit the in-flight file is closed and writes continue in // snowluma-YYYY-MM-DD.1.log, .2.log, ... // at the same date. Files older than the retain window are unlinked on -// startup and again on each day rollover. +// startup and on each day rollover. // -// Disabled via SNOWLUMA_LOG_FILE=0. Any I/O failure during init or write -// degrades silently to console-only; we deliberately do NOT use the -// logger from inside this module to avoid recursion. +// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally +// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O +// failure during init or write degrades silently to console-only — we +// deliberately do NOT use the logger from inside this module to avoid +// recursion. import fs from 'node:fs'; import path from 'node:path'; @@ -57,73 +61,59 @@ interface OpenFile { path: string; } -export class FileTransport { +/** + * Owns one output directory: keeps at most one open WriteStream, handles + * daily rollover, per-file size cap, and retention cleanup. The shared + * top-level dir uses one of these; each per-UIN sub-dir gets its own. + */ +class FileWriter { private disabled = false; - private readonly dir: string; - private readonly maxBytes: number; - private readonly retainDays: number; - private shared: OpenFile | null = null; - - constructor() { - this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; - this.maxBytes = - parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; - this.retainDays = parsePositiveInt( - process.env.SNOWLUMA_LOG_RETAIN_DAYS, - DEFAULT_RETAIN_DAYS, - ); - - if (process.env.SNOWLUMA_LOG_FILE === '0') { - this.disabled = true; - return; - } + private file: OpenFile | null = null; + constructor( + private readonly dir: string, + private readonly maxBytes: number, + private readonly retainDays: number, + ) { try { - fs.mkdirSync(this.dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true }); } catch (err) { this.disabled = true; - // Direct stderr — logger would recurse. // eslint-disable-next-line no-console console.error( - `[logger] failed to create log dir ${this.dir}: ${err instanceof Error ? err.message : String(err)}`, + `[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`, ); return; } - this.cleanup(); } - /** True when file output is suppressed (env disable or init failure). */ get isDisabled(): boolean { return this.disabled; } - /** Current target file path (or null if disabled / not yet opened). */ get currentPath(): string | null { - return this.shared?.path ?? null; + return this.file?.path ?? null; } - write(line: string): void { + write(data: string, bytes: number): void { if (this.disabled) return; const today = todayString(); - const data = stripAnsi(line) + '\n'; - const bytes = Buffer.byteLength(data, 'utf8'); - this.ensureForToday(today); - if (!this.shared) return; + if (!this.file) return; - if (this.shared.bytes + bytes > this.maxBytes && this.shared.bytes > 0) { + if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) { this.rotateBySize(); - if (!this.shared) return; + if (!this.file) return; } - this.shared.stream.write(data); - this.shared.bytes += bytes; + this.file.stream.write(data); + this.file.bytes += bytes; } close(): Promise { - const f = this.shared; - this.shared = null; + const f = this.file; + this.file = null; if (!f) return Promise.resolve(); return new Promise((resolve) => { try { @@ -135,37 +125,36 @@ export class FileTransport { } private ensureForToday(today: string): void { - if (this.shared && this.shared.date === today) return; + if (this.file && this.file.date === today) return; - if (this.shared) { + if (this.file) { try { - this.shared.stream.end(); + this.file.stream.end(); } catch { /* ignore */ } - this.shared = null; - // Day rolled over — also a good moment to evict stale files. + this.file = null; this.cleanup(); } - // Find the highest existing split index for today and continue appending - // to it (so multiple process starts on the same day share files). + // Resume from the highest existing split index for today (so two + // process starts on the same day share files / don't clobber). let idx = 0; while (fs.existsSync(this.pathFor(today, idx + 1))) idx++; - this.shared = this.openFile(today, idx); + this.file = this.openFile(today, idx); } private rotateBySize(): void { - if (!this.shared) return; - const date = this.shared.date; + if (!this.file) return; + const date = this.file.date; try { - this.shared.stream.end(); + this.file.stream.end(); } catch { /* ignore */ } - let next = this.shared.splitIndex + 1; + let next = this.file.splitIndex + 1; while (fs.existsSync(this.pathFor(date, next))) next++; - this.shared = this.openFile(date, next); + this.file = this.openFile(date, next); } private openFile(date: string, splitIndex: number): OpenFile | null { @@ -210,8 +199,7 @@ export class FileTransport { const m = FILE_RE.exec(name); if (!m) continue; const dateStr = m[1]!; - const fileDate = dateOf(dateStr); - if (fileDate.getTime() < cutoff) { + if (dateOf(dateStr).getTime() < cutoff) { try { fs.unlinkSync(path.join(this.dir, name)); } catch { @@ -222,6 +210,75 @@ export class FileTransport { } } +export class FileTransport { + private readonly dir: string; + private readonly maxBytes: number; + private readonly retainDays: number; + private readonly enabled: boolean; + private readonly perUinEnabled: boolean; + private shared: FileWriter | null = null; + private perUin = new Map(); + + constructor() { + this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; + this.maxBytes = + parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; + this.retainDays = parsePositiveInt( + process.env.SNOWLUMA_LOG_RETAIN_DAYS, + DEFAULT_RETAIN_DAYS, + ); + this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0'; + this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0'; + + if (this.enabled) { + const w = new FileWriter(this.dir, this.maxBytes, this.retainDays); + this.shared = w.isDisabled ? null : w; + } + } + + /** True when no file output will happen (env disable or init failure). */ + get isDisabled(): boolean { + return !this.shared; + } + + /** Current shared-file path (or null if disabled / not yet opened). */ + get currentPath(): string | null { + return this.shared?.currentPath ?? null; + } + + /** Path of the per-UIN file for the given UIN, if open. */ + perUinPath(uin: number): string | null { + return this.perUin.get(uin)?.currentPath ?? null; + } + + write(line: string, uin?: number): void { + if (!this.shared) return; + const data = stripAnsi(line) + '\n'; + const bytes = Buffer.byteLength(data, 'utf8'); + + this.shared.write(data, bytes); + + if (uin !== undefined && this.perUinEnabled) { + let w = this.perUin.get(uin); + if (!w) { + w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays); + if (w.isDisabled) return; + this.perUin.set(uin, w); + } + w.write(data, bytes); + } + } + + async close(): Promise { + const closes: Promise[] = []; + if (this.shared) closes.push(this.shared.close()); + for (const w of this.perUin.values()) closes.push(w.close()); + this.shared = null; + this.perUin.clear(); + await Promise.all(closes); + } +} + let singleton: FileTransport | null = null; export function getFileTransport(): FileTransport { @@ -229,7 +286,7 @@ export function getFileTransport(): FileTransport { return singleton; } -/** Reset state between tests. Closes the active file handle. */ +/** Reset state between tests. Closes all active file handles. */ export async function _resetFileTransportForTesting(): Promise { if (singleton) await singleton.close(); singleton = null; diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index a2c2b411..bb63fa0e 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -8,14 +8,26 @@ export interface LogEntry { time: string; level: LogLevel; scope: string; + /** QQ uin, when the source logger was derived via `.child({ uin })`. */ + uin?: number; message: string; line: string; } interface LogOptions { scope: string; + uin?: number; + /** Free-form meta carried across `.child(...)` calls. Currently only + * `uin` is rendered, but the bag is preserved for future fields + * (requestId / traceId / etc.). */ + meta?: Record; } +// Fixed-width slot for the UIN tag in rendered output so the [Scope] +// column stays vertically aligned across lines with and without a UIN. +// Width covers `[1234567890]` (12 chars); anything longer just won't pad. +const UIN_SLOT_WIDTH = 12; + const LEVEL_WEIGHT: Record = { debug: 10, info: 20, @@ -79,19 +91,26 @@ function currentTime(): string { return `${hh}:${mm}:${ss}`; } -function render(level: LogLevel, scope: string, args: unknown[]): string { +function render(level: LogLevel, options: LogOptions, args: unknown[]): string { const message = format(...args); const ts = currentTime(); const label = LEVEL_LABEL[level].padEnd(5, ' '); + const uinTag = options.uin !== undefined ? `[${options.uin}]` : ''; + const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH); if (!useColor()) { - return `${ts} ${label} [${scope}] ${message}`; + return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`; } const cTs = ansi(COLOR_DIM, ts); const cLabel = ansi(COLOR_CODE[level], label); - const cScope = ansi(COLOR_SCOPE, `[${scope}]`); - return `${cTs} ${cLabel} ${cScope} ${message}`; + // Pad first, then color only the visible tag so escape codes don't eat + // into the alignment width. + const cUin = uinTag + ? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length) + : ' '.repeat(UIN_SLOT_WIDTH); + const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`); + return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`; } function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { @@ -99,12 +118,13 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { // see log-file-transport.ts. const passesConsole = shouldLog(level); const message = format(...args); - const line = render(level, options.scope, args); + const line = render(level, options, args); const entry: LogEntry = { id: nextLogId++, time: new Date().toISOString(), level, scope: options.scope, + ...(options.uin !== undefined ? { uin: options.uin } : {}), message, line, }; @@ -123,8 +143,9 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { } // File transport always sees every level (debug-and-up) for post-mortem - // value; ANSI stripping happens inside the transport. - getFileTransport().write(line); + // value; ANSI stripping happens inside the transport. UIN routes the + // line to its per-account sub-file in addition to the shared one. + getFileTransport().write(line, options.uin); } /** @@ -155,15 +176,33 @@ export interface Logger { success: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; + /** + * Derive a new logger that inherits this one's scope and carries + * additional metadata. Currently `uin` is the only key with rendering + * support (shown in the `[UIN]` slot and routed to a per-UIN file); + * other keys are preserved on the options bag for forward compat. + */ + child: (meta: { uin?: number; [k: string]: unknown }) => Logger; +} + +function makeLogger(opts: LogOptions): Logger { + return { + debug: (...args: unknown[]) => emit('debug', opts, args), + info: (...args: unknown[]) => emit('info', opts, args), + success: (...args: unknown[]) => emit('success', opts, args), + warn: (...args: unknown[]) => emit('warn', opts, args), + error: (...args: unknown[]) => emit('error', opts, args), + child: (meta) => { + const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin; + return makeLogger({ + scope: opts.scope, + uin: nextUin, + meta: { ...(opts.meta ?? {}), ...meta }, + }); + }, + }; } export function createLogger(scope: string): Logger { - const options: LogOptions = { scope }; - return { - debug: (...args: unknown[]) => emit('debug', options, args), - info: (...args: unknown[]) => emit('info', options, args), - success: (...args: unknown[]) => emit('success', options, args), - warn: (...args: unknown[]) => emit('warn', options, args), - error: (...args: unknown[]) => emit('error', options, args), - }; + return makeLogger({ scope }); } diff --git a/packages/core/tests/logger.test.ts b/packages/core/tests/logger.test.ts new file mode 100644 index 00000000..7ac141ea --- /dev/null +++ b/packages/core/tests/logger.test.ts @@ -0,0 +1,180 @@ +// Tests for the core logger API: +// - createLogger() output shape (scope rendering) +// - .child({ uin }) derivation and the [UIN] slot in the rendered line +// - LogEntry.uin propagation to subscribers +// - File transport per-UIN fan-out (and the SNOWLUMA_LOG_PER_UIN=0 gate) +// +// We exercise the file transport via its real fs paths against tmpdirs +// so the test catches integration regressions, not just unit shape. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createLogger, subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { _resetFileTransportForTesting } from '../src/utils/log-file-transport'; + +let tmpDir: string; +const ENV_KEYS = [ + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_PER_UIN', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', + 'SNOWLUMA_LOG_LEVEL', + 'NO_COLOR', +] as const; +const savedEnv: Record = {}; + +function setEnv(env: Partial>): void { + for (const [k, v] of Object.entries(env)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +} + +beforeEach(async () => { + for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-logger-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_PER_UIN: '1', + SNOWLUMA_LOG_MAX_MB: '5', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + NO_COLOR: '1', + }); + await _resetFileTransportForTesting(); +}); + +afterEach(async () => { + await _resetFileTransportForTesting(); + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('createLogger', () => { + it('renders [Scope] with the empty UIN slot when no child binding', async () => { + const log = createLogger('Bridge'); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('hello'); + unsub(); + + expect(captured).toHaveLength(1); + const entry = captured[0]!; + expect(entry.scope).toBe('Bridge'); + expect(entry.uin).toBeUndefined(); + // Plain-text line shape (NO_COLOR=1): + // HH:MM:SS · INFO_ · _<12 blank uin slot>_ · [Bridge] · msg + // where · = single separator space inside the template literal. + const tail = entry.line.slice(9); // drop "HH:MM:SS " + expect(tail).toBe(`INFO ${' '.repeat(12)} [Bridge] hello`); + }); + + it('child({ uin }) derives a logger that stamps the [UIN] slot', async () => { + const log = createLogger('Bridge').child({ uin: 12345 }); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('via child'); + unsub(); + + expect(captured).toHaveLength(1); + const entry = captured[0]!; + expect(entry.uin).toBe(12345); + expect(entry.scope).toBe('Bridge'); + // "[12345]" is 7 chars; padEnd to 12 leaves 5 trailing spaces inside + // the slot, then 1 separator space before "[Bridge]". + const tail = entry.line.slice(9); + expect(tail).toBe(`INFO [12345] [Bridge] via child`); + }); + + it('child() does not mutate the parent logger', async () => { + const parent = createLogger('Bridge'); + const childA = parent.child({ uin: 100 }); + const childB = parent.child({ uin: 200 }); + + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + parent.info('parent'); + childA.info('a'); + childB.info('b'); + unsub(); + + expect(captured.map((e) => e.uin)).toEqual([undefined, 100, 200]); + }); + + it('child() can be chained; later uin wins, earlier meta is preserved', async () => { + const log = createLogger('Bridge').child({ uin: 100, foo: 'first' }).child({ bar: 'second' }); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('chained'); + unsub(); + + // uin from first child survives through the second (which only sets bar) + expect(captured).toHaveLength(1); + expect(captured[0]!.uin).toBe(100); + }); + + it('writes the per-UIN sub-file in addition to the shared file', async () => { + const log = createLogger('Bridge').child({ uin: 67890 }); + log.info('to file'); + await _resetFileTransportForTesting(); + + const sharedFiles = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(sharedFiles).toHaveLength(1); + const sharedPath = path.join(tmpDir, sharedFiles[0]!); + expect(fs.readFileSync(sharedPath, 'utf8')).toContain('[67890]'); + + const uinSubDir = path.join(tmpDir, '67890'); + expect(fs.existsSync(uinSubDir)).toBe(true); + const uinFiles = fs.readdirSync(uinSubDir).filter((f) => f.endsWith('.log')); + expect(uinFiles).toHaveLength(1); + expect(fs.readFileSync(path.join(uinSubDir, uinFiles[0]!), 'utf8')) + .toContain('to file'); + }); + + it('lines without uin go only to the shared file', async () => { + const log = createLogger('App'); + log.info('no uin here'); + await _resetFileTransportForTesting(); + + const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(shared).toHaveLength(1); + // No numeric sub-dirs should have been created. + const subDirs = fs.readdirSync(tmpDir, { withFileTypes: true }) + .filter((d) => d.isDirectory()) + .map((d) => d.name); + expect(subDirs).toHaveLength(0); + }); + + it('SNOWLUMA_LOG_PER_UIN=0 suppresses the per-UIN sub-file but keeps the shared one', async () => { + setEnv({ SNOWLUMA_LOG_PER_UIN: '0' }); + await _resetFileTransportForTesting(); + + const log = createLogger('Bridge').child({ uin: 9999 }); + log.info('one line'); + await _resetFileTransportForTesting(); + + expect(fs.existsSync(path.join(tmpDir, '9999'))).toBe(false); + const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(shared).toHaveLength(1); + expect(fs.readFileSync(path.join(tmpDir, shared[0]!), 'utf8')) + .toContain('one line'); + }); + + it('SNOWLUMA_LOG_FILE=0 also suppresses per-UIN files', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + await _resetFileTransportForTesting(); + + const log = createLogger('Bridge').child({ uin: 1 }); + log.info('hi'); + await _resetFileTransportForTesting(); + + const entries = fs.readdirSync(tmpDir); + expect(entries).toHaveLength(0); + }); +});