feat(log): memory-only trace level + request correlation + chokepoint tracing
Debugging from user-supplied logs was impossible: a successful action left one terse, over-summarized debug line and nothing about what it sent QQ or what QQ returned. Add full-chain tracing that stays off disk so it scales to hundreds of groups. common: - New `trace` level (below debug). Never written to file — it lives only in an in-memory ring + the WebUI stream, so the high-volume full chain costs no disk. `emit` early-returns for trace before format/render (and before any lazy producer) when trace isn't active → ~free at the default level. - Dedicated O(1) circular ring for trace (default 5000, SNOWLUMA_TRACE_BUFFER), separate from the normal 1000-entry buffer (also switched off array .shift); getRecentLogs merges both by id. - request-context.ts: AsyncLocalStorage request id. The logger auto-stamps `[req#N]` on every line in a request's async chain — across packages, zero signature threading — and records it on the entry. - log-summary.renderParamsVerbose: deep render of params (nested structure, per-string cap, total budget, token/password/secret redaction). chokepoints (auto-cover every action without touching 100+ handlers): - onebot api-handler: wrap each action in a request id (only when trace is live); trace the full params on entry and status+elapsed on exit; the terse debug breadcrumb still persists to file, failures still warn. - core bridge.sendRawPacket: trace on success (cmd, sizes, elapsed); warn on errorCode!=0 / no response (cmd, code, message) so disk keeps real problems. - protocol highway: fold the bare console.log lines into the logger (trace). webui: trace as the lowest filterable level; render the `[req#N]` tag and let search match it. Server needs no change — LOG_LEVELS, getRecentLogs and the SSE stream carry it through.
This commit is contained in:
9 files changed
+375
-30
No files matched your search
@@ -49,3 +49,70 @@ export function summarizeParams(params: unknown): string {
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const VERBOSE_STRING_MAX = 200;
|
||||
const VERBOSE_TOTAL_MAX = 1500;
|
||||
// Keys whose values must never be rendered — tokens, passwords, secrets.
|
||||
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
|
||||
|
||||
/**
|
||||
* Deep, debug-grade render of a params object for the `trace` level: shows the
|
||||
* full nested structure (message segments, nested objects) so a reproduction
|
||||
* is legible — unlike {@link summarizeParams}, which collapses nested values.
|
||||
*
|
||||
* Three guards keep it safe and bounded:
|
||||
* - per-string cap (long values like base64 image data become `"…<N B>"`),
|
||||
* - total output budget (so a giant payload can't flood the buffer),
|
||||
* - key-based redaction (token / password / secret → `"***"`).
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
let budget = VERBOSE_TOTAL_MAX;
|
||||
|
||||
const walk = (value: unknown, key?: string): string => {
|
||||
if (budget <= 0) return '…';
|
||||
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string': {
|
||||
const truncated =
|
||||
value.length > VERBOSE_STRING_MAX
|
||||
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
|
||||
: value;
|
||||
const out = JSON.stringify(truncated);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint': {
|
||||
const out = String(value);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const parts: string[] = [];
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(walk(item));
|
||||
}
|
||||
return `[${parts.join(',')}]`;
|
||||
}
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(`${k}:${walk(v, k)}`);
|
||||
}
|
||||
return `{${parts.join(',')}}`;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
+104
-17
@@ -1,7 +1,8 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { currentRequestId } from './request-context';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -10,6 +11,8 @@ export interface LogEntry {
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
@@ -26,6 +29,7 @@ interface LogOptions {
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
@@ -34,6 +38,7 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
@@ -42,6 +47,7 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
@@ -53,13 +59,55 @@ const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
@@ -75,7 +123,7 @@ function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
@@ -110,15 +158,16 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
@@ -129,28 +178,46 @@ function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
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.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
|
||||
// `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.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const message = format(...realArgs);
|
||||
const line = render(level, options, realArgs, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
@@ -162,10 +229,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 always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,8 +247,14 @@ export function closeLogger(): Promise<void> {
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
// Merge the normal + trace rings by id (ids are monotonic, so id order is
|
||||
// chronological). The trace ring is empty unless trace level is/was active,
|
||||
// so the common case is just the normal ring with no sort.
|
||||
const merged = traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return merged.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
@@ -191,6 +265,13 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
@@ -207,6 +288,7 @@ export interface Logger {
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
@@ -226,3 +308,8 @@ function makeLogger(opts: LogOptions): Logger {
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
// 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';
|
||||
@@ -0,0 +1,35 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
|
||||
* it never overflows to a non-integer; `0` is skipped so "no id" stays
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with `id` bound as the ambient request id for the entire async
|
||||
* chain it spawns. Any logger call anywhere in that chain — across packages,
|
||||
* across awaits — picks it up via {@link currentRequestId} with no signature
|
||||
* threading. Used by the OneBot action handler to correlate a request's whole
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
@@ -129,12 +131,29 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
}
|
||||
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
if (!result.success || result.errorCode !== 0) {
|
||||
// QQ-side rejection or transport failure — the usual root cause when an
|
||||
// action misbehaves. Warn (persisted) with cmd + code so a user's log
|
||||
// shows exactly where the chain broke.
|
||||
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd, result.errorCode, result.gotResponse,
|
||||
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
|
||||
} else {
|
||||
// Happy path — memory-only trace so the full chain shows under the
|
||||
// request's [req#N] when debugging, without flooding disk.
|
||||
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { summarizeParams } from '@snowluma/common/log-summary';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
|
||||
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { register as registerExtended } from './actions/extended';
|
||||
import { register as registerFriend } from './actions/friend';
|
||||
@@ -109,13 +109,33 @@ export class ApiHandler {
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
// Correlate the whole request — entry, every outbound packet it triggers,
|
||||
// and the exit — under one `[req#N]` tag via AsyncLocalStorage. Only pay
|
||||
// the wrap + id allocation when trace is actually live, so the default
|
||||
// path stays allocation-free.
|
||||
if (getLogLevel() !== 'trace') {
|
||||
return this.runAction(action, handler, params);
|
||||
}
|
||||
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params));
|
||||
}
|
||||
|
||||
private async runAction(
|
||||
action: string,
|
||||
handler: ActionHandler,
|
||||
params: JsonObject,
|
||||
): 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.
|
||||
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.
|
||||
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
|
||||
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
return await handler(params);
|
||||
const response = await handler(params);
|
||||
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
|
||||
return response;
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
getRecentLogs,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('shows the full nested structure (message segments), unlike the shallow summary', () => {
|
||||
const out = renderParamsVerbose({
|
||||
group_id: 123,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }, { type: 'at', data: { qq: '456' } }],
|
||||
});
|
||||
expect(out).toContain('group_id:123');
|
||||
expect(out).toContain('text');
|
||||
expect(out).toContain('"hello"');
|
||||
expect(out).toContain('"456"');
|
||||
});
|
||||
|
||||
it('truncates long strings (e.g. base64) with a size marker', () => {
|
||||
const big = 'A'.repeat(5000);
|
||||
const out = renderParamsVerbose({ file: `base64://${big}` });
|
||||
expect(out).toContain('base64://');
|
||||
expect(out).toContain('…<'); // truncation marker
|
||||
expect(out).toContain('B>');
|
||||
expect(out.length).toBeLessThan(2000); // bounded by the total budget
|
||||
});
|
||||
|
||||
it('redacts sensitive keys at any depth', () => {
|
||||
const out = renderParamsVerbose({
|
||||
access_token: 'super-secret-value',
|
||||
nested: { password: 'hunter2', SECRET: 'x', ok: 'visible' },
|
||||
});
|
||||
expect(out).not.toContain('super-secret-value');
|
||||
expect(out).not.toContain('hunter2');
|
||||
expect(out).toContain('"***"');
|
||||
expect(out).toContain('"visible"'); // non-sensitive keys still rendered
|
||||
});
|
||||
|
||||
it('handles circular references without throwing', () => {
|
||||
const a: Record<string, unknown> = { name: 'a' };
|
||||
a.self = a;
|
||||
expect(() => renderParamsVerbose(a)).not.toThrow();
|
||||
expect(renderParamsVerbose(a)).toContain('[circular]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('logger trace level + request correlation', () => {
|
||||
let prevLevel: string;
|
||||
|
||||
beforeEach(() => {
|
||||
prevLevel = getLogLevel();
|
||||
});
|
||||
afterEach(() => {
|
||||
setLogLevel(prevLevel);
|
||||
});
|
||||
|
||||
it('captures trace into the in-memory buffer only when the level is trace', () => {
|
||||
const log = createLogger('Test.Trace');
|
||||
const marker = `trace-marker-${Math.trunc(performance.now())}-${getRecentLogs(1).length}`;
|
||||
|
||||
setLogLevel('info');
|
||||
log.trace('off %s', marker);
|
||||
expect(getRecentLogs(2000).some((e) => e.message.includes(marker))).toBe(false);
|
||||
|
||||
setLogLevel('trace');
|
||||
log.trace('on %s', marker);
|
||||
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
|
||||
expect(hit).toBeDefined();
|
||||
expect(hit?.level).toBe('trace');
|
||||
});
|
||||
|
||||
it('does NOT evaluate a lazy producer when trace is off (the efficiency guarantee)', () => {
|
||||
const log = createLogger('Test.Lazy');
|
||||
const produce = vi.fn(() => ['lazy payload']);
|
||||
|
||||
setLogLevel('info');
|
||||
log.trace(produce);
|
||||
expect(produce).not.toHaveBeenCalled();
|
||||
|
||||
setLogLevel('trace');
|
||||
log.trace(produce);
|
||||
expect(produce).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stamps the ambient request id onto entries emitted inside runWithRequestId', () => {
|
||||
const log = createLogger('Test.Req');
|
||||
setLogLevel('trace');
|
||||
const marker = `req-marker-${Math.trunc(performance.now())}`;
|
||||
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
runWithRequestId(4242, () => {
|
||||
expect(currentRequestId()).toBe(4242);
|
||||
log.trace('inside %s', marker);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
|
||||
expect(hit?.req).toBe(4242);
|
||||
expect(hit?.line).toContain('[req#4242]');
|
||||
});
|
||||
});
|
||||
@@ -8,11 +8,13 @@ import type {
|
||||
ReqDataHighwayHead,
|
||||
RespDataHighwayHead,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const log = createLogger('Highway');
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
@@ -69,7 +71,7 @@ export async function fetchHighwaySession(bridge: BridgeContext): Promise<Highwa
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||
log.trace('session %s:%d sig=%dB', session.host, session.port, (session.sigSession as Uint8Array).length);
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -286,6 +288,6 @@ export async function uploadHighwayHttp(
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
log.trace('uploaded %d/%d bytes', offset, bytes.length);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import type { LogEntry, LogLevel } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
const levelClass: Record<LogLevel, string> = {
|
||||
trace: 'text-muted-foreground/60',
|
||||
debug: 'text-muted-foreground',
|
||||
info: 'text-primary',
|
||||
success: 'text-success',
|
||||
@@ -19,7 +20,7 @@ const levelClass: Record<LogLevel, string> = {
|
||||
error: 'text-destructive',
|
||||
};
|
||||
|
||||
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
/** Show a locale time when the backend sends an ISO timestamp (it does);
|
||||
* fall back to the raw string otherwise so we never render "Invalid Date". */
|
||||
@@ -98,7 +99,8 @@ export function LogsPage() {
|
||||
return (
|
||||
l.message.toLowerCase().includes(f) ||
|
||||
l.scope.toLowerCase().includes(f) ||
|
||||
l.level.toLowerCase().includes(f)
|
||||
l.level.toLowerCase().includes(f) ||
|
||||
(l.req !== undefined && String(l.req).includes(f))
|
||||
);
|
||||
});
|
||||
}, [logs, filter, enabledLevels]);
|
||||
@@ -223,6 +225,11 @@ export function LogsPage() {
|
||||
{log.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
|
||||
{log.req !== undefined && (
|
||||
<span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] text-primary tabular-nums" title="请求关联号">
|
||||
#{log.req}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="min-w-0 whitespace-pre-wrap break-all">{log.message}</span>
|
||||
</motion.div>
|
||||
|
||||
@@ -124,7 +124,7 @@ export interface SystemInfo {
|
||||
};
|
||||
}
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
export type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -132,6 +132,8 @@ export interface LogEntry {
|
||||
level: LogLevel;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Request correlation id, when emitted inside a request scope. */
|
||||
req?: number;
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
|
||||
Reference in new issue
Block a user