diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c69b3ca8..413024bc 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,7 +1,7 @@ import { BridgeManager } from './bridge/manager'; import { OneBotManager } from './onebot/manager'; import { loadRuntimeConfig } from './common/runtime'; -import { createLogger } from './utils/logger'; +import { closeLogger, createLogger } from './utils/logger'; import { HookManager } from './hook/hook-manager'; const runtimeConfig = loadRuntimeConfig(); @@ -38,13 +38,17 @@ async function main() { } } - // Graceful shutdown - process.on('SIGINT', () => { - log.warn('Shutting down...'); + // Graceful shutdown: dispose managers, await log flush, then exit. + // SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path. + const shutdown = (signal: string) => async () => { + log.warn(`Shutting down (${signal})...`); oneBotManager.dispose(); hookManager.dispose(); + await closeLogger(); process.exit(0); - }); + }; + process.on('SIGINT', shutdown('SIGINT')); + process.on('SIGTERM', shutdown('SIGTERM')); } function resolveAutoLoad(fromConfig: boolean | undefined): boolean { @@ -57,7 +61,8 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean { return fromConfig === true; } -main().catch((error) => { +main().catch(async (error) => { log.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); + await closeLogger(); process.exit(1); }); diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/core/src/utils/log-file-transport.ts new file mode 100644 index 00000000..211a126d --- /dev/null +++ b/packages/core/src/utils/log-file-transport.ts @@ -0,0 +1,236 @@ +// 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.1.log, .2.log, ... +// at the same date. Files older than the retain window are unlinked on +// startup and again 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. + +import fs from 'node:fs'; +import path from 'node:path'; + +const DEFAULT_DIR = 'logs'; +const DEFAULT_MAX_MB = 50; +const DEFAULT_RETAIN_DAYS = 7; +const FILE_PREFIX = 'snowluma-'; +const FILE_SUFFIX = '.log'; +const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/; + +// eslint-disable-next-line no-control-regex +const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g; +// eslint-disable-next-line no-control-regex +const CTRL_RE = /[\x00-\x1A\x1C-\x1F\x7F]/g; + +function parsePositiveInt(v: string | undefined, dflt: number): number { + if (!v) return dflt; + const n = Number.parseInt(v, 10); + return Number.isFinite(n) && n > 0 ? n : dflt; +} + +function todayString(d: Date = new Date()): string { + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +function dateOf(s: string): Date { + const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10)); + return new Date(y!, m! - 1, d!); +} + +function stripAnsi(line: string): string { + return line.replace(ANSI_RE, '').replace(CTRL_RE, ''); +} + +interface OpenFile { + stream: fs.WriteStream; + bytes: number; + date: string; + splitIndex: number; + path: string; +} + +export class FileTransport { + 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; + } + + try { + fs.mkdirSync(this.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)}`, + ); + 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; + } + + write(line: string): 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.shared.bytes + bytes > this.maxBytes && this.shared.bytes > 0) { + this.rotateBySize(); + if (!this.shared) return; + } + + this.shared.stream.write(data); + this.shared.bytes += bytes; + } + + close(): Promise { + const f = this.shared; + this.shared = null; + if (!f) return Promise.resolve(); + return new Promise((resolve) => { + try { + f.stream.end(() => resolve()); + } catch { + resolve(); + } + }); + } + + private ensureForToday(today: string): void { + if (this.shared && this.shared.date === today) return; + + if (this.shared) { + try { + this.shared.stream.end(); + } catch { + /* ignore */ + } + this.shared = null; + // Day rolled over — also a good moment to evict stale files. + 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). + let idx = 0; + while (fs.existsSync(this.pathFor(today, idx + 1))) idx++; + this.shared = this.openFile(today, idx); + } + + private rotateBySize(): void { + if (!this.shared) return; + const date = this.shared.date; + try { + this.shared.stream.end(); + } catch { + /* ignore */ + } + let next = this.shared.splitIndex + 1; + while (fs.existsSync(this.pathFor(date, next))) next++; + this.shared = this.openFile(date, next); + } + + private openFile(date: string, splitIndex: number): OpenFile | null { + const p = this.pathFor(date, splitIndex); + try { + let bytes = 0; + try { + bytes = fs.statSync(p).size; + } catch { + /* file doesn't exist yet */ + } + const stream = fs.createWriteStream(p, { flags: 'a' }); + stream.on('error', (err) => { + // eslint-disable-next-line no-console + console.error(`[logger] file write error on ${p}: ${err.message}`); + }); + return { stream, bytes, date, splitIndex, path: p }; + } catch (err) { + // eslint-disable-next-line no-console + console.error( + `[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`, + ); + return null; + } + } + + private pathFor(date: string, splitIndex: number): string { + const tail = splitIndex > 0 ? `.${splitIndex}` : ''; + return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`); + } + + private cleanup(): void { + let entries: string[]; + try { + entries = fs.readdirSync(this.dir); + } catch { + return; + } + const retainMs = this.retainDays * 24 * 60 * 60 * 1000; + const cutoff = Date.now() - retainMs; + for (const name of entries) { + const m = FILE_RE.exec(name); + if (!m) continue; + const dateStr = m[1]!; + const fileDate = dateOf(dateStr); + if (fileDate.getTime() < cutoff) { + try { + fs.unlinkSync(path.join(this.dir, name)); + } catch { + /* ignore */ + } + } + } + } +} + +let singleton: FileTransport | null = null; + +export function getFileTransport(): FileTransport { + if (!singleton) singleton = new FileTransport(); + return singleton; +} + +/** Reset state between tests. Closes the active file handle. */ +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 534bb7b0..a2c2b411 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -1,4 +1,5 @@ import { format } from 'util'; +import { getFileTransport } from './log-file-transport'; type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error'; @@ -94,7 +95,9 @@ function render(level: LogLevel, scope: string, args: unknown[]): string { } function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { - if (!shouldLog(level)) return; + // Console / subscriber level filter. File output is debug-and-up always; + // see log-file-transport.ts. + const passesConsole = shouldLog(level); const message = format(...args); const line = render(level, options.scope, args); const entry: LogEntry = { @@ -105,16 +108,33 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { message, line, }; - logEntries.push(entry); - if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift(); - for (const subscriber of logSubscribers) subscriber(entry); - const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; - // Strip ASCII control characters before writing to terminal to prevent - // BEL (0x07) in user-provided strings (e.g. group member names) from - // triggering Windows system beep sounds. ESC (0x1B) is preserved so the - // ANSI color sequences emitted by render() actually reach the terminal. - // eslint-disable-next-line no-control-regex - stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + + if (passesConsole) { + logEntries.push(entry); + if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift(); + for (const subscriber of logSubscribers) subscriber(entry); + const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; + // Strip ASCII control characters before writing to terminal to prevent + // BEL (0x07) in user-provided strings (e.g. group member names) from + // triggering Windows system beep sounds. ESC (0x1B) is preserved so the + // ANSI color sequences emitted by render() actually reach the terminal. + // eslint-disable-next-line no-control-regex + stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + } + + // File transport always sees every level (debug-and-up) for post-mortem + // value; ANSI stripping happens inside the transport. + getFileTransport().write(line); +} + +/** + * Flush and close the underlying log file. Call from shutdown hooks + * (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal + * buffer makes it to disk. Returns a promise that resolves once the OS + * has finalized the write. + */ +export function closeLogger(): Promise { + return getFileTransport().close(); } export function getRecentLogs(limit = 300): LogEntry[] { diff --git a/packages/core/tests/log-file-transport.test.ts b/packages/core/tests/log-file-transport.test.ts new file mode 100644 index 00000000..b07c6dcb --- /dev/null +++ b/packages/core/tests/log-file-transport.test.ts @@ -0,0 +1,159 @@ +// Tests for the file transport that backs the SnowLuma logger. +// Each test gets its own tmp dir and a fresh FileTransport so env / state +// from one test never bleeds into another. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { FileTransport } from '../src/utils/log-file-transport'; + +let tmpDir: string; +const ENV_KEYS = [ + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', +] 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; + } +} + +function listLogFiles(dir: string): string[] { + return fs.readdirSync(dir).filter((f) => f.endsWith('.log')).sort(); +} + +beforeEach(() => { + for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-log-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_MAX_MB: '1', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + }); +}); + +afterEach(() => { + 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 }); + vi.useRealTimers(); +}); + +describe('FileTransport', () => { + it('creates today\'s file and writes a single line', async () => { + const t = new FileTransport(); + t.write('hello world'); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files).toHaveLength(1); + expect(files[0]).toMatch(/^snowluma-\d{4}-\d{2}-\d{2}\.log$/); + expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')).toBe('hello world\n'); + }); + + it('strips ANSI color escapes and ASCII control chars before writing', async () => { + const t = new FileTransport(); + t.write('\x1b[36mINFO\x1b[0m \x07[Bridge] msg'); + await t.close(); + + const [file] = listLogFiles(tmpDir); + expect(fs.readFileSync(path.join(tmpDir, file!), 'utf8')).toBe('INFO [Bridge] msg\n'); + }); + + it('rolls into a .1 file when the current file exceeds the size cap', async () => { + // 1MB cap from beforeEach. Write ~2 MB to force a single rotation. + const t = new FileTransport(); + const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024 + for (let i = 0; i < 2048; i++) t.write(oneKB); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files.length).toBeGreaterThanOrEqual(2); + const base = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.log$/.test(f)); + const split = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.1\.log$/.test(f)); + expect(base).toBeDefined(); + expect(split).toBeDefined(); + }); + + it('opens a new file when the day rolls over mid-process', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0)); + const t = new FileTransport(); + t.write('day-one line'); + vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1)); + t.write('day-two line'); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files).toContain('snowluma-2026-05-18.log'); + expect(files).toContain('snowluma-2026-05-19.log'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')) + .toContain('day-one line'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')) + .toContain('day-two line'); + }); + + it('deletes files older than the retention window on startup', async () => { + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + const t = new FileTransport(); + t.write('fresh'); + await t.close(); + + expect(fs.existsSync(stalePath)).toBe(false); + }); + + it('keeps files inside the retention window', async () => { + const recent = new Date(); + recent.setDate(recent.getDate() - 2); + const recentName = `snowluma-${recent.getFullYear()}-${String(recent.getMonth() + 1).padStart(2, '0')}-${String(recent.getDate()).padStart(2, '0')}.log`; + const recentPath = path.join(tmpDir, recentName); + fs.writeFileSync(recentPath, 'recent\n'); + + const t = new FileTransport(); + await t.close(); + + expect(fs.existsSync(recentPath)).toBe(true); + }); + + it('SNOWLUMA_LOG_FILE=0 suppresses all file output', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const t = new FileTransport(); + t.write('should not be written'); + await t.close(); + + expect(t.isDisabled).toBe(true); + expect(listLogFiles(tmpDir)).toHaveLength(0); + }); + + it('appends to the existing today file across restarts', async () => { + const a = new FileTransport(); + a.write('before restart'); + await a.close(); + + const b = new FileTransport(); + b.write('after restart'); + await b.close(); + + const files = listLogFiles(tmpDir); + expect(files).toHaveLength(1); + expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')) + .toBe('before restart\nafter restart\n'); + }); + + it('exposes the current file path while open', () => { + const t = new FileTransport(); + t.write('x'); + expect(t.currentPath).not.toBeNull(); + expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/); + }); +}); diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index 64bbf402..4870d273 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -12,6 +12,13 @@ export default defineConfig({ }, test: { include: ['tests/**/*.test.ts'], - environment: 'node' + environment: 'node', + // Suppress the logger's file transport during tests so the suite + // doesn't litter cwd with logs/snowluma-*.log files. Tests that + // explicitly cover file output set their own SNOWLUMA_LOG_FILE='1' + // + SNOWLUMA_LOG_DIR=. + env: { + SNOWLUMA_LOG_FILE: '0' + } } });