diff --git a/README.md b/README.md index 657e5b65..bfbd41b1 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整 | 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` | | 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` | | 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` | +| 文件日志级别 | debug | `SNOWLUMA_LOG_FILE_LEVEL` | 环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。 diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index 6e2f83c0..858b57d2 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -114,27 +114,45 @@ function resolveMinLevel(): LogLevel { return 'info'; } +const _rawFileLevel = (process.env.SNOWLUMA_LOG_FILE_LEVEL ?? '').toLowerCase(); + +function resolveFileMinLevel(): LogLevel { + if (_rawFileLevel === 'trace') return 'debug'; + if (_rawFileLevel === 'debug' || _rawFileLevel === 'info' || _rawFileLevel === 'success' || + _rawFileLevel === 'warn' || _rawFileLevel === 'error') { + return _rawFileLevel; + } + return 'debug'; +} + // Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but // setLogLevel() lets WebUI / SDK callers flip it without a restart. -// Only governs console + ring buffer + subscribers; the file -// transport always sees debug-and-up regardless. +// Only governs console + ring buffer + subscribers; +// the file transport level is seeded independently from +// SNOWLUMA_LOG_FILE_LEVEL (default debug) +// and is not affected by setLogLevel(). let currentLevel: LogLevel = resolveMinLevel(); +let currentFileLevel: LogLevel = resolveFileMinLevel(); function shouldLog(level: LogLevel): boolean { return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel]; } +function shouldLogToFile(level: LogLevel): boolean { + return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel]; +} + export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error']; export function getLogLevel(): LogLevel { return currentLevel; } -/** - * Change the console / subscriber level at runtime. Invalid input is - * a no-op (returns false). File transport is unaffected — it always - * sees every level so post-mortems remain useful. - */ + +// Change the console / subscriber level at runtime. +// Invalid input is a no-op (returns false). +// Does not affect the file transport log level. + export function setLogLevel(level: string): boolean { const lower = String(level).toLowerCase(); if (!LOG_LEVELS.includes(lower as LogLevel)) return false; @@ -184,15 +202,15 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n } function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { - // Console / subscriber level filter. File output is debug-and-up always; - // see log-file-transport.ts. + // Console / subscriber level filter. + // File output is gated independently by currentFileLevel. const passesConsole = shouldLog(level); - // `trace` never touches disk and is the high-volume full-chain stream. When - // it won't reach the console/memory buffer either (level not dialed to - // trace), bail BEFORE format/render AND before evaluating any lazy producer - // — this is what keeps full-chain tracing ~free at the default level even - // with hundreds of groups. + // `trace` is the high-volume full-chain diagnostic stream, intentionally + // excluded from disk to avoid I/O saturation. When console is not dialed + // to trace, the early return below skips format/render/disk entirely. + // Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory; + // trace never reaches disk regardless. if (level === 'trace' && !passesConsole) return; // Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer @@ -230,11 +248,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); } - // File transport sees debug-and-up for post-mortem value; `trace` is - // memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI - // stripping happens inside the transport. UIN routes the line to its - // per-account sub-file in addition to the shared one. - if (level !== 'trace') getFileTransport().write(line, options.uin); + // File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL, + // default debug). `trace` is memory / WebUI only (omitted here to avoid huge + // on-disk volume). ANSI stripping happens inside the transport. UIN routes + // the line to its per-account sub-file in addition to the shared one. + if (level !== 'trace' && shouldLogToFile(level)) getFileTransport().write(line, options.uin); } /** @@ -314,3 +332,13 @@ export function createLogger(scope: string): Logger { // stamping is a logging concern. Re-exported here so callers import the // whole logging surface from one place. export { nextRequestId, runWithRequestId, currentRequestId } from './request-context'; + +// Warn once at module load if SNOWLUMA_LOG_FILE_LEVEL was set to 'trace' +// (trace is intentionally excluded from disk for I/O reasons — see emit()). +if (_rawFileLevel === 'trace') { + emit('warn', { scope: 'logger' }, [ + 'SNOWLUMA_LOG_FILE_LEVEL=trace is not supported — ' + + 'trace is never written to disk. File level clamped to debug.', + ]); +} + diff --git a/packages/common/tests/logger.test.ts b/packages/common/tests/logger.test.ts index 5c0cf87a..7993414d 100644 --- a/packages/common/tests/logger.test.ts +++ b/packages/common/tests/logger.test.ts @@ -1,11 +1,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -// The file transport writes to disk; stub it so the test has no side effects. -vi.mock('../src/log-file-transport', () => ({ - getFileTransport: () => ({ write: () => {} }), +// Capture file transport writes via a spy so tests can assert on what reaches +// the file. vi.hoisted() runs before vi.mock() so the spy is available inside +// the factory (which is hoisted by vitest). +const { fileWriteSpy } = vi.hoisted(() => ({ + fileWriteSpy: vi.fn(), })); -import { createLogger, subscribeLogs, type LogEntry } from '../src/logger'; +vi.mock('../src/log-file-transport', () => ({ + getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }), +})); + +import { + createLogger, + getLogLevel, + getRecentLogs, + setLogLevel, + subscribeLogs, + type LogEntry, +} from '../src/logger'; // Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp // shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored @@ -55,3 +68,169 @@ describe('logger UIN slot padding', () => { expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[')); }); }); + +// ─── Independent file-level filtering ───────────────────────────────────── +// The file transport level is set independently from the console level via +// SNOWLUMA_LOG_FILE_LEVEL (default debug). These tests verify that the +// correct levels reach or skip the file transport under default settings. + +describe('file output gating', () => { + beforeEach(() => { + fileWriteSpy.mockClear(); + }); + + it('writes debug to file under the default file level', () => { + createLogger('Test').debug('breadcrumb'); + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + expect(fileWriteSpy).toHaveBeenCalledWith( + expect.stringContaining('breadcrumb'), + undefined, + ); + }); + + it('writes info to file under the default file level', () => { + createLogger('Test').info('item'); + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('writes success to file under the default file level', () => { + createLogger('Test').success('ok'); + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('writes warn to file under the default file level', () => { + createLogger('Test').warn('heads-up'); + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('writes error to file under the default file level', () => { + createLogger('Test').error('problem'); + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('never writes trace to file regardless of level settings', () => { + // trace does not pass the console gate at the default log level (info), + // so emit() short-circuits before reaching the file-write decision. + // Even if console were set to trace, the hard guard at the end of emit() + // would still block the file write — this test just confirms no write + // under default conditions. + createLogger('Test').trace('full chain'); + expect(fileWriteSpy).not.toHaveBeenCalled(); + }); +}); + +// ─── setLogLevel vs file output ──────────────────────────────────────────── +// setLogLevel() only changes the console / subscriber level. The file output +// level is independent and should not be affected. + +describe('setLogLevel does not affect file output', () => { + let savedLevel: ReturnType; + + beforeEach(() => { + fileWriteSpy.mockClear(); + savedLevel = getLogLevel(); + }); + + afterEach(() => { + setLogLevel(savedLevel); + }); + + it('still writes debug to file after raising console to warn', () => { + setLogLevel('warn'); + createLogger('Test').debug('breadcrumb'); + // File level is still debug → debug reaches file even though console + // (now at warn) skips it. + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('still writes info to file after raising console to error', () => { + setLogLevel('error'); + createLogger('Test').info('item'); + // File level still debug → info passes shouldLogToFile. + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); + + it('still writes to file even when console is dialled down to trace', () => { + setLogLevel('trace'); + createLogger('Test').debug('reachable'); + // Console lets everything through at trace; file still at debug. + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + }); +}); + +// ─── SNOWLUMA_LOG_FILE_LEVEL=trace warning ───────────────────────────────── +// When the environment variable is set to 'trace' at startup, the logger emits +// a one-time warning via its own infrastructure (no raw stderr.write). The +// real file level is clamped to debug regardless. + +describe('SNOWLUMA_LOG_FILE_LEVEL=trace warning', () => { + const SAVED = process.env.SNOWLUMA_LOG_FILE_LEVEL; + + afterEach(async () => { + // Restore the env and reset module cache so the next test gets a clean + // logger with the real env value. + if (SAVED === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED; + vi.resetModules(); + }); + + it('emits a single warn entry at module load with scope logger', async () => { + process.env.SNOWLUMA_LOG_FILE_LEVEL = 'trace'; + vi.resetModules(); + + // Dynamic import gives us a fresh logger module that sees the trace env + // var during resolveFileMinLevel() — the warning fires inside emit() + // at the bottom of the module body. + const fresh = await import('../src/logger'); + + const warnLogs = fresh + .getRecentLogs() + .filter((e: { level: string }) => e.level === 'warn'); + + // The module-init warning + no other warn entries should be in the ring. + expect(warnLogs).toHaveLength(1); + expect(warnLogs[0]!.scope).toBe('logger'); + expect(warnLogs[0]!.message).toContain( + 'SNOWLUMA_LOG_FILE_LEVEL=trace is not supported', + ); + expect(warnLogs[0]!.message).toContain('clamped to debug'); + + fresh.closeLogger(); + }); + + it('emits no warning when the env var is not trace', async () => { + delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + vi.resetModules(); + + const fresh = await import('../src/logger'); + + const warnLogs = fresh + .getRecentLogs() + .filter((e: { level: string }) => e.level === 'warn'); + + const traceWarnings = warnLogs.filter( + (e: { scope: string }) => e.scope === 'logger', + ); + expect(traceWarnings).toHaveLength(0); + + fresh.closeLogger(); + }); + + it('emits no warning for info', async () => { + process.env.SNOWLUMA_LOG_FILE_LEVEL = 'info'; + vi.resetModules(); + + const fresh = await import('../src/logger'); + + const warnLogs = fresh + .getRecentLogs() + .filter((e: { level: string }) => e.level === 'warn'); + + const traceWarnings = warnLogs.filter( + (e: { scope: string }) => e.scope === 'logger', + ); + expect(traceWarnings).toHaveLength(0); + + fresh.closeLogger(); + }); +}); diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 8efdee77..21976e74 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -262,8 +262,8 @@ export class ApiHandler { params: JsonObject, sink?: StreamSink, ): Promise { - // Terse breadcrumb to the log file (debug, always persisted): lets the - // operator grep "what did the bot get asked to do" in post-mortems. + // Terse breadcrumb to the log file (debug, which is written to disk under the default + // file level): lets the operator grep "what did the bot get asked to do" in post-mortems. this.log.debug('%s params=%s', action, summarizeParams(params)); // Full request shape, memory-only (trace). Lazy producer → the deep render // only runs when trace is live. diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index dfada8f8..c5c8514b 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -510,7 +510,7 @@ export function LogsPage() {
服务端日志级别 - · 仅影响控制台 / 实时流,文件始终落盘 debug + · 仅影响控制台 / 实时流;文件落盘级别由环境变量决定,默认debug
{LEVELS.map((lv) => { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 87a8ddde..4b488692 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -249,7 +249,8 @@ export interface ApiClient { list(limit?: number): Promise; /** Subscribe to the SSE log stream. Returns a disposer. */ stream(options: LogsStreamOptions): () => void; - /** Current console / subscriber level. File output is always debug. */ + /** Current console / subscriber level. File logging level is set via + * SNOWLUMA_LOG_FILE_LEVEL (default: debug), independent of this method. */ getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>; /** Change the console / subscriber level at runtime. No restart needed. */ setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>;