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:
DrSmoothl committed 2026-05-18 13:15:05 +08:00
1 parent 4a49c55775
commit 4c513c015d
7 files changed
+154 -12

No files matched your search

@@ -8,10 +8,10 @@ import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry } from '@/types';
import type { LogEntry, LogLevel } from '@/types';
import { useApi } from '@/lib/api';
const levelClass: Record<LogEntry['level'], string> = {
const levelClass: Record<LogLevel, string> = {
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
@@ -19,7 +19,7 @@ const levelClass: Record<LogEntry['level'], string> = {
error: 'text-destructive',
};
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export function LogsPage() {
const api = useApi();
@@ -27,8 +27,10 @@ export function LogsPage() {
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
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 [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
const [levelBusy, setLevelBusy] = useState(false);
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
@@ -44,6 +46,25 @@ export function LogsPage() {
void 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(() => {
return api.logs.stream({
onLine: (entry) => {
@@ -75,7 +96,7 @@ export function LogsPage() {
});
}, [logs, filter, enabledLevels]);
const toggleLevel = (lv: LogEntry['level']) => {
const toggleLevel = (lv: LogLevel) => {
setEnabledLevels((prev) => {
const next = new Set(prev);
if (next.has(lv)) next.delete(lv);
@@ -121,7 +142,8 @@ export function LogsPage() {
</div>
</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) => {
const active = enabledLevels.has(lv);
return (
@@ -142,6 +164,31 @@ export function LogsPage() {
})}
</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">
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
<ScrollArea
+4 -1
View File
@@ -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 { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
@@ -84,6 +84,9 @@ class HttpApiClient implements ApiClient {
return data.list ?? [];
},
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 }),
};
}
+5
View File
@@ -1,6 +1,7 @@
import type {
HookProcessInfo,
LogEntry,
LogLevel,
OneBotConfig,
QQInfo,
SystemInfo,
@@ -69,6 +70,10 @@ 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. */
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. */
+5 -1
View File
@@ -101,10 +101,14 @@ export interface SystemInfo {
};
}
export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
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;
message: string;
line: string;