fix(logging): harden file level configuration

Make persisted log filtering predictable across supported startup settings while rejecting configurations that could silently retain more data than intended.

Keep the first WebUI login credential available without weakening normal log thresholds, clarify the operator-facing behavior, and strengthen regression coverage across isolated environments and explicit file-output disablement.
This commit is contained in:
DrSmoothl committed 2026-07-30 10:27:43 +08:00
1 parent 227a62f2ad
commit 655226d9d7
6 files changed
+212 -181

No files matched your search

+3 -2
View File
@@ -101,9 +101,10 @@ 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` 仅控制单个日志分卷大小,不是日志树总量上限。
以上环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。
文件日志等级可通过 `SNOWLUMA_LOG_FILE_LEVEL` 单独设置为 `debug`、`info`、`success`、`warn` 或 `error`,默认为 `debug`。该启动参数不写入 `config/runtime.json`,也不受 WebUI 实时日志等级影响;TRACE 始终不落盘。
## 选择接入方式
+35 -23
View File
@@ -4,6 +4,7 @@ import { sanitizeLogLine } from './log-sanitize';
import { currentRequestId } from './request-context';
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
type FileLogLevel = Exclude<LogLevel, 'trace'>;
export interface LogEntry {
id: number;
@@ -114,15 +115,18 @@ function resolveMinLevel(): LogLevel {
return 'info';
}
const _rawFileLevel = (process.env.SNOWLUMA_LOG_FILE_LEVEL ?? '').toLowerCase();
function resolveFileMinLevel(): FileLogLevel {
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
if (raw === undefined || raw.trim() === '') return 'debug';
function resolveFileMinLevel(): LogLevel {
if (_rawFileLevel === 'trace') return 'debug';
if (_rawFileLevel === 'debug' || _rawFileLevel === 'info' || _rawFileLevel === 'success' ||
_rawFileLevel === 'warn' || _rawFileLevel === 'error') {
return _rawFileLevel;
const normalized = raw.trim().toLowerCase();
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
normalized === 'warn' || normalized === 'error') {
return normalized;
}
return 'debug';
throw new TypeError(
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
);
}
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
@@ -132,7 +136,7 @@ function resolveFileMinLevel(): LogLevel {
// SNOWLUMA_LOG_FILE_LEVEL (default debug)
// and is not affected by setLogLevel().
let currentLevel: LogLevel = resolveMinLevel();
let currentFileLevel: LogLevel = resolveFileMinLevel();
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
@@ -201,10 +205,17 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter.
// File output is gated independently by currentFileLevel.
const passesConsole = shouldLog(level);
function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
forceFile = false,
): void {
// Console / subscriber and file filters are independent. If no destination
// accepts the record, stop before formatting or building a LogEntry.
const passesConsole = forceFile || shouldLog(level);
const passesFile = level !== 'trace' && (forceFile || shouldLogToFile(level));
if (!passesConsole && !passesFile) return;
// `trace` is the high-volume full-chain diagnostic stream, intentionally
// excluded from disk to avoid I/O saturation. When console is not dialed
@@ -252,7 +263,9 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// 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);
if (passesFile) {
getFileTransport().write(line, options.uin);
}
}
/**
@@ -328,17 +341,16 @@ export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}
export function logInitialWebuiCredentials(password: string): void {
emit(
'info',
{ scope: 'WebUI' },
['initial credentials: user=admin password=%s', password],
true,
);
}
// Request-correlation helpers live alongside the logger since `[req#N]`
// 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.',
]);
}
+124 -151
View File
@@ -1,21 +1,25 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
delete process.env.SNOWLUMA_LOG_LEVEL;
return {
externalFileLevel: savedFileLevel,
externalLogLevel: savedLogLevel,
fileWriteSpy: vi.fn(),
};
});
// 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(),
}));
// the file.
vi.mock('../src/log-file-transport', () => ({
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
}));
import {
createLogger,
getLogLevel,
getRecentLogs,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '../src/logger';
@@ -70,167 +74,136 @@ describe('logger UIN slot padding', () => {
});
// ─── 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.
const SAVED_FILE_LEVEL = externalFileLevel;
async function loadLoggerForFileLevel(level?: string) {
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
vi.resetModules();
fileWriteSpy.mockClear();
return import('../src/logger');
}
afterEach(() => {
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
vi.resetModules();
fileWriteSpy.mockClear();
});
afterAll(() => {
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
});
describe('file output gating', () => {
beforeEach(() => {
fileWriteSpy.mockClear();
const cases = [
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
{ level: 'success', expected: ['success', 'warn', 'error'] },
{ level: 'warn', expected: ['warn', 'error'] },
{ level: 'error', expected: ['error'] },
] as const;
for (const testCase of cases) {
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
const fresh = await loadLoggerForFileLevel(testCase.level);
const log = fresh.createLogger('Test');
fresh.setLogLevel('trace');
log.trace('trace');
log.debug('debug');
log.info('info');
log.success('success');
log.warn('warn');
log.error('error');
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
expect(messages).toEqual(testCase.expected);
});
}
it('accepts surrounding whitespace and mixed case', async () => {
const fresh = await loadLoggerForFileLevel(' INFO ');
const log = fresh.createLogger('Test');
log.debug('debug');
log.info('info');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
});
it('writes debug to file under the default file level', () => {
createLogger('Test').debug('breadcrumb');
it.each(['trace', 'verbose', 'erorr'])(
'rejects unsupported file level %s at startup',
async (level) => {
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
);
expect(fileWriteSpy).not.toHaveBeenCalled();
},
);
it('does not let the runtime console level change file output', async () => {
const fresh = await loadLoggerForFileLevel('info');
const log = fresh.createLogger('Test');
fresh.setLogLevel('error');
log.info('persisted-info');
fresh.setLogLevel('trace');
log.debug('filtered-debug');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(
expect.stringContaining('breadcrumb'),
expect.stringContaining('persisted-info'),
undefined,
);
});
it('writes info to file under the default file level', () => {
createLogger('Test').info('item');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
});
it('skips rendering when both console and file filters reject a record', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const rendered = vi.fn(() => 'expensive');
const value = { [Symbol.toPrimitive]: rendered };
it('writes success to file under the default file level', () => {
createLogger('Test').success('ok');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
});
fresh.createLogger('Test').debug('value=%s', value);
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(rendered).not.toHaveBeenCalled();
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.
it('keeps trace out of files at every file threshold', async () => {
const fresh = await loadLoggerForFileLevel('debug');
fresh.setLogLevel('trace');
describe('setLogLevel does not affect file output', () => {
let savedLevel: ReturnType<typeof getLogLevel>;
fresh.createLogger('Test').trace('full chain');
beforeEach(() => {
fileWriteSpy.mockClear();
savedLevel = getLogLevel();
expect(fileWriteSpy).not.toHaveBeenCalled();
});
afterEach(() => {
setLogLevel(savedLevel);
});
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
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.
fresh.logInitialWebuiCredentials('secret');
unsubscribe();
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
level: 'info',
scope: 'WebUI',
message: 'initial credentials: user=admin password=secret',
});
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();
expect(fileWriteSpy).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
undefined,
);
});
});
+10 -2
View File
@@ -6,7 +6,15 @@ import {
configureFileTransport,
getLogStorageStatus,
} from '@snowluma/common/log-file-transport';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import {
createLogger,
getLogLevel,
getRecentLogs,
logInitialWebuiCredentials,
LOG_LEVELS,
setLogLevel,
subscribeLogs,
} from '@snowluma/common/logger';
import {
loadOneBotConfig,
OneBotConfigValidationError,
@@ -489,7 +497,7 @@ export async function initWebUI(
log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。');
log.info(' Log in and change the password now; it will not be shown again.');
log.info('────────────────────────────────────────────────────────────────');
log.info('initial credentials: user=admin password=%s', initialPassword);
logInitialWebuiCredentials(initialPassword);
log.info('════════════════════════════════════════════════════════════════');
} else if (auth.mustChangePassword()) {
log.warn('password change is still required');
+39 -2
View File
@@ -7,11 +7,30 @@
// 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 { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
const { externalFileLevel, externalLogLevel } = vi.hoisted(() => {
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
delete process.env.SNOWLUMA_LOG_LEVEL;
return {
externalFileLevel: savedFileLevel,
externalLogLevel: savedLogLevel,
};
});
import {
createLogger,
getLogLevel,
logInitialWebuiCredentials,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import {
_resetFileTransportForTesting,
configureFileTransport,
@@ -26,6 +45,7 @@ const ENV_KEYS = [
'SNOWLUMA_LOG_MAX_TOTAL_MB',
'SNOWLUMA_LOG_RETAIN_DAYS',
'SNOWLUMA_LOG_LEVEL',
'SNOWLUMA_LOG_FILE_LEVEL',
'NO_COLOR',
] as const;
const savedEnv: Record<string, string | undefined> = {};
@@ -61,6 +81,13 @@ afterEach(async () => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
afterAll(() => {
if (externalFileLevel === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = externalFileLevel;
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
});
describe('createLogger', () => {
it('renders [Scope] with the empty UIN slot when no child binding', async () => {
const log = createLogger('Bridge');
@@ -183,6 +210,16 @@ describe('createLogger', () => {
expect(entries).toHaveLength(0);
});
it('SNOWLUMA_LOG_FILE=0 suppresses bootstrap notices too', async () => {
setEnv({ SNOWLUMA_LOG_FILE: '0' });
await _resetFileTransportForTesting();
logInitialWebuiCredentials('secret');
await _resetFileTransportForTesting();
expect(fs.readdirSync(tmpDir)).toHaveLength(0);
});
it('applies the runtime storage policy through the singleton before writing', async () => {
const status = await configureFileTransport({
maxTotalMb: 3,
@@ -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) => {