feat(logger): runtime log level toggle via WebUI
The console / subscriber level was captured at module load
(`const MIN_LEVEL = resolveMinLevel()`), so any change to
SNOWLUMA_LOG_LEVEL after Node started had no effect — restart was
the only way to flip levels, which makes "go to debug for 30s to
see what's happening" pretty painful.
logger.ts now keeps `currentLevel` mutable and exports
setLogLevel() / getLogLevel(). The env var still seeds it on
startup; nothing about the boot-time behavior changes. File
transport remains unaffected — it always sees debug-and-up.
WebUI gets two new endpoints, both behind the existing auth
middleware:
GET /api/logs/level → { level, levels }
POST /api/logs/level body → { level: 'debug' } updates it
Logs page picks up a "服务端级别" row of pills next to the
existing client-side filter pills, so an operator can flip the
console firehose on/off in one click without touching env vars
or restarting the bot. The label clarifies that file logging
stays at debug regardless.
This commit is contained in:
7 files changed
+154
-12
No files matched your search
@@ -68,10 +68,32 @@ function resolveMinLevel(): LogLevel {
|
|||||||
return 'info';
|
return 'info';
|
||||||
}
|
}
|
||||||
|
|
||||||
const MIN_LEVEL = resolveMinLevel();
|
// 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.
|
||||||
|
let currentLevel: LogLevel = resolveMinLevel();
|
||||||
|
|
||||||
function shouldLog(level: LogLevel): boolean {
|
function shouldLog(level: LogLevel): boolean {
|
||||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
|
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LOG_LEVELS: readonly LogLevel[] = ['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.
|
||||||
|
*/
|
||||||
|
export function setLogLevel(level: string): boolean {
|
||||||
|
const lower = String(level).toLowerCase();
|
||||||
|
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||||
|
currentLevel = lower as LogLevel;
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function useColor(): boolean {
|
function useColor(): boolean {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { serve } from '@hono/node-server';
|
|||||||
import { serveStatic } from '@hono/node-server/serve-static';
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
import { Hono, type Context } from 'hono';
|
import { Hono, type Context } from 'hono';
|
||||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger';
|
||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import type { OneBotManager } from '../onebot/manager';
|
import type { OneBotManager } from '../onebot/manager';
|
||||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||||
@@ -340,6 +340,20 @@ export async function initWebUI(
|
|||||||
return c.json({ list: getRecentLogs(limit) });
|
return c.json({ list: getRecentLogs(limit) });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.get('/api/logs/level', (c) => {
|
||||||
|
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/logs/level', async (c) => {
|
||||||
|
const body = await c.req.json().catch(() => null) as { level?: unknown } | null;
|
||||||
|
const next = typeof body?.level === 'string' ? body.level : '';
|
||||||
|
if (!setLogLevel(next)) {
|
||||||
|
return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400);
|
||||||
|
}
|
||||||
|
log.info('console log level set to %s via WebUI', getLogLevel());
|
||||||
|
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||||
|
});
|
||||||
|
|
||||||
app.get('/api/logs/stream', (c) => {
|
app.get('/api/logs/stream', (c) => {
|
||||||
const stream = new ReadableStream({
|
const stream = new ReadableStream({
|
||||||
start(controller) {
|
start(controller) {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { createLogger, subscribeLogs, type LogEntry } from '../src/utils/logger';
|
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||||
import { _resetFileTransportForTesting } from '../src/utils/log-file-transport';
|
import { _resetFileTransportForTesting } from '../src/utils/log-file-transport';
|
||||||
|
|
||||||
let tmpDir: string;
|
let tmpDir: string;
|
||||||
@@ -178,3 +178,50 @@ describe('createLogger', () => {
|
|||||||
expect(entries).toHaveLength(0);
|
expect(entries).toHaveLength(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('setLogLevel / getLogLevel — runtime level toggle', () => {
|
||||||
|
// Each test restores whatever level was active going in so the suite
|
||||||
|
// ordering can't bleed state between specs.
|
||||||
|
let saved: ReturnType<typeof getLogLevel>;
|
||||||
|
beforeEach(() => { saved = getLogLevel(); });
|
||||||
|
afterEach(() => { setLogLevel(saved); });
|
||||||
|
|
||||||
|
it('setLogLevel updates getLogLevel for valid input', () => {
|
||||||
|
expect(setLogLevel('warn')).toBe(true);
|
||||||
|
expect(getLogLevel()).toBe('warn');
|
||||||
|
expect(setLogLevel('debug')).toBe(true);
|
||||||
|
expect(getLogLevel()).toBe('debug');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setLogLevel rejects unknown values without mutating state', () => {
|
||||||
|
setLogLevel('info');
|
||||||
|
expect(setLogLevel('nonsense')).toBe(false);
|
||||||
|
expect(getLogLevel()).toBe('info');
|
||||||
|
expect(setLogLevel('')).toBe(false);
|
||||||
|
expect(setLogLevel('Verbose')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setLogLevel is case-insensitive', () => {
|
||||||
|
expect(setLogLevel('WARN')).toBe(true);
|
||||||
|
expect(getLogLevel()).toBe('warn');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('changes which entries reach the ring buffer / subscribers', () => {
|
||||||
|
const captured: LogEntry[] = [];
|
||||||
|
const unsub = subscribeLogs((e) => captured.push(e));
|
||||||
|
const log = createLogger('LevelTest');
|
||||||
|
|
||||||
|
setLogLevel('warn');
|
||||||
|
log.debug('hidden-debug');
|
||||||
|
log.info('hidden-info');
|
||||||
|
log.warn('visible-warn');
|
||||||
|
log.error('visible-error');
|
||||||
|
|
||||||
|
unsub();
|
||||||
|
|
||||||
|
const messages = captured
|
||||||
|
.filter((e) => e.scope === 'LevelTest')
|
||||||
|
.map((e) => e.message);
|
||||||
|
expect(messages).toEqual(['visible-warn', 'visible-error']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -8,10 +8,10 @@ import { Input } from '@/components/ui/input';
|
|||||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import type { LogEntry } from '@/types';
|
import type { LogEntry, LogLevel } from '@/types';
|
||||||
import { useApi } from '@/lib/api';
|
import { useApi } from '@/lib/api';
|
||||||
|
|
||||||
const levelClass: Record<LogEntry['level'], string> = {
|
const levelClass: Record<LogLevel, string> = {
|
||||||
debug: 'text-muted-foreground',
|
debug: 'text-muted-foreground',
|
||||||
info: 'text-primary',
|
info: 'text-primary',
|
||||||
success: 'text-success',
|
success: 'text-success',
|
||||||
@@ -19,7 +19,7 @@ const levelClass: Record<LogEntry['level'], string> = {
|
|||||||
error: 'text-destructive',
|
error: 'text-destructive',
|
||||||
};
|
};
|
||||||
|
|
||||||
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
|
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||||
|
|
||||||
export function LogsPage() {
|
export function LogsPage() {
|
||||||
const api = useApi();
|
const api = useApi();
|
||||||
@@ -27,8 +27,10 @@ export function LogsPage() {
|
|||||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||||
const [paused, setPaused] = useState(false);
|
const [paused, setPaused] = useState(false);
|
||||||
const [filter, setFilter] = useState('');
|
const [filter, setFilter] = useState('');
|
||||||
const [enabledLevels, setEnabledLevels] = useState<Set<LogEntry['level']>>(new Set(LEVELS));
|
const [enabledLevels, setEnabledLevels] = useState<Set<LogLevel>>(new Set(LEVELS));
|
||||||
const [confirmClear, setConfirmClear] = useState(false);
|
const [confirmClear, setConfirmClear] = useState(false);
|
||||||
|
const [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
|
||||||
|
const [levelBusy, setLevelBusy] = useState(false);
|
||||||
const endRef = useRef<HTMLDivElement | null>(null);
|
const endRef = useRef<HTMLDivElement | null>(null);
|
||||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
@@ -44,6 +46,25 @@ export function LogsPage() {
|
|||||||
void loadLogs();
|
void loadLogs();
|
||||||
}, [loadLogs]);
|
}, [loadLogs]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
api.logs.getLevel().then(({ level }) => setServerLevel(level)).catch((err) => {
|
||||||
|
console.error('getLevel', err);
|
||||||
|
});
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
|
const changeServerLevel = useCallback(async (lv: LogLevel) => {
|
||||||
|
if (lv === serverLevel || levelBusy) return;
|
||||||
|
setLevelBusy(true);
|
||||||
|
try {
|
||||||
|
const { level } = await api.logs.setLevel(lv);
|
||||||
|
setServerLevel(level);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('setLevel', err);
|
||||||
|
} finally {
|
||||||
|
setLevelBusy(false);
|
||||||
|
}
|
||||||
|
}, [api, serverLevel, levelBusy]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return api.logs.stream({
|
return api.logs.stream({
|
||||||
onLine: (entry) => {
|
onLine: (entry) => {
|
||||||
@@ -75,7 +96,7 @@ export function LogsPage() {
|
|||||||
});
|
});
|
||||||
}, [logs, filter, enabledLevels]);
|
}, [logs, filter, enabledLevels]);
|
||||||
|
|
||||||
const toggleLevel = (lv: LogEntry['level']) => {
|
const toggleLevel = (lv: LogLevel) => {
|
||||||
setEnabledLevels((prev) => {
|
setEnabledLevels((prev) => {
|
||||||
const next = new Set(prev);
|
const next = new Set(prev);
|
||||||
if (next.has(lv)) next.delete(lv);
|
if (next.has(lv)) next.delete(lv);
|
||||||
@@ -121,7 +142,8 @@ export function LogsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
|
<div className="flex flex-wrap items-center gap-1 px-5 pb-2">
|
||||||
|
<span className="mr-2 text-[11px] text-muted-foreground/80">视图过滤</span>
|
||||||
{LEVELS.map((lv) => {
|
{LEVELS.map((lv) => {
|
||||||
const active = enabledLevels.has(lv);
|
const active = enabledLevels.has(lv);
|
||||||
return (
|
return (
|
||||||
@@ -142,6 +164,31 @@ export function LogsPage() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
|
||||||
|
<span className="mr-2 text-[11px] text-muted-foreground/80" title="文件落盘始终为 debug,此处仅控制控制台 / 实时流的级别">
|
||||||
|
服务端级别
|
||||||
|
</span>
|
||||||
|
{LEVELS.map((lv) => {
|
||||||
|
const active = serverLevel === lv;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={lv}
|
||||||
|
type="button"
|
||||||
|
onClick={() => void changeServerLevel(lv)}
|
||||||
|
disabled={levelBusy || serverLevel === null}
|
||||||
|
className={cn(
|
||||||
|
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
active
|
||||||
|
? cn('border-primary', levelClass[lv], 'bg-primary/10')
|
||||||
|
: 'border-border text-muted-foreground/70 hover:text-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{lv.toUpperCase()}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
|
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
|
||||||
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
|
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
|
||||||
<ScrollArea
|
<ScrollArea
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
|
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||||
import {
|
import {
|
||||||
@@ -84,6 +84,9 @@ class HttpApiClient implements ApiClient {
|
|||||||
return data.list ?? [];
|
return data.list ?? [];
|
||||||
},
|
},
|
||||||
stream: (options) => this.openLogStream(options),
|
stream: (options) => this.openLogStream(options),
|
||||||
|
getLevel: () => this.getJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`),
|
||||||
|
setLevel: (level) =>
|
||||||
|
this.postJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`, { level }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
HookProcessInfo,
|
HookProcessInfo,
|
||||||
LogEntry,
|
LogEntry,
|
||||||
|
LogLevel,
|
||||||
OneBotConfig,
|
OneBotConfig,
|
||||||
QQInfo,
|
QQInfo,
|
||||||
SystemInfo,
|
SystemInfo,
|
||||||
@@ -69,6 +70,10 @@ export interface ApiClient {
|
|||||||
list(limit?: number): Promise<LogEntry[]>;
|
list(limit?: number): Promise<LogEntry[]>;
|
||||||
/** Subscribe to the SSE log stream. Returns a disposer. */
|
/** Subscribe to the SSE log stream. Returns a disposer. */
|
||||||
stream(options: LogsStreamOptions): () => void;
|
stream(options: LogsStreamOptions): () => void;
|
||||||
|
/** Current console / subscriber level. File output is always debug. */
|
||||||
|
getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||||
|
/** Change the console / subscriber level at runtime. No restart needed. */
|
||||||
|
setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Escape hatch for endpoints not yet wrapped above. */
|
/** Escape hatch for endpoints not yet wrapped above. */
|
||||||
|
|||||||
@@ -101,10 +101,14 @@ export interface SystemInfo {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||||
|
|
||||||
export interface LogEntry {
|
export interface LogEntry {
|
||||||
id: number;
|
id: number;
|
||||||
time: string;
|
time: string;
|
||||||
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
|
level: LogLevel;
|
||||||
|
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||||
|
uin?: number;
|
||||||
scope: string;
|
scope: string;
|
||||||
message: string;
|
message: string;
|
||||||
line: string;
|
line: string;
|
||||||
|
|||||||
Reference in new issue
Block a user