feat(common): configure file log level

Allow operators to control how much diagnostic information is retained in file logs independently from live console output.

Document the new startup setting and add regression coverage for its default behavior, runtime independence, and unsupported configurations.
This commit is contained in:
Werewolf-Wu authored and DrSmoothl committed 2026-07-30 10:04:52 +08:00
1 parent e5f256f4dc
commit 227a62f2ad
6 files changed
+236 -27

No files matched your search

+1
View File
@@ -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` 仅控制单个日志分卷大小,不是日志树总量上限。
+47 -19
View File
@@ -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.',
]);
}
+183 -4
View File
@@ -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<typeof getLogLevel>;
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();
});
});
+2 -2
View File
@@ -262,8 +262,8 @@ export class ApiHandler {
params: JsonObject,
sink?: StreamSink,
): Promise<import('./types').ApiResponse> {
// 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.
@@ -510,7 +510,7 @@ export function LogsPage() {
<div>
<div className="mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
<span className="text-xs font-medium text-foreground">服务端日志级别</span>
<span className="text-xs text-muted-foreground">· 仅影响控制台 / 实时流,文件始终落盘 debug</span>
<span className="text-xs text-muted-foreground">· 仅影响控制台 / 实时流;文件落盘级别由环境变量决定,默认debug</span>
</div>
<div className="inline-flex flex-wrap gap-1 rounded-lg bg-muted/60 p-1">
{LEVELS.map((lv) => {
+2 -1
View File
@@ -249,7 +249,8 @@ export interface ApiClient {
list(limit?: number): Promise<LogEntry[]>;
/** 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[] }>;