-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdebugLogger.ts
More file actions
233 lines (210 loc) · 6.64 KB
/
Copy pathdebugLogger.ts
File metadata and controls
233 lines (210 loc) · 6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { AsyncLocalStorage } from 'node:async_hooks';
import util from 'node:util';
import { Storage } from '../config/storage.js';
import { updateSymlink } from './symlink.js';
import {
getTraceContext,
type TraceContext,
} from '../telemetry/trace-context.js';
type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
export interface DebugLogSession {
getSessionId: () => string;
}
export interface DebugLogger {
isEnabled: () => boolean;
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
}
let ensureDebugDirPromise: Promise<void> | null = null;
let ensuredDebugDirPath: string | null = null;
let hasWriteFailure = false;
let globalSession: DebugLogSession | null = null;
const sessionContext = new AsyncLocalStorage<DebugLogSession | false>();
export function isDebugLogFileEnabled(): boolean {
const value = process.env['QWEN_DEBUG_LOG_FILE'];
if (!value) return false;
const normalized = value.trim().toLowerCase();
return !['', '0', 'false', 'off', 'no'].includes(normalized);
}
function getActiveSession(): DebugLogSession | null {
const contextSession = sessionContext.getStore();
if (contextSession === false) return null;
return contextSession ?? globalSession;
}
function ensureDebugDirExists(): Promise<void> {
const debugDirPath = Storage.getGlobalDebugDir();
if (!ensureDebugDirPromise || ensuredDebugDirPath !== debugDirPath) {
ensuredDebugDirPath = debugDirPath;
ensureDebugDirPromise = fs
.mkdir(debugDirPath, { recursive: true })
.then(() => undefined)
.catch(() => {
hasWriteFailure = true;
ensureDebugDirPromise = null;
ensuredDebugDirPath = null;
});
}
return ensureDebugDirPromise ?? Promise.resolve();
}
function formatArgs(args: unknown[]): string {
return args
.map((arg) => {
if (arg instanceof Error) {
return arg.stack ?? `${arg.name}: ${arg.message}`;
}
return arg;
})
.map((arg) => (typeof arg === 'string' ? arg : util.inspect(arg)))
.join(' ');
}
/**
* Builds a log line in the format:
* `2026-01-23T06:58:02.011Z [DEBUG] [TAG] [trace_id=xxx span_id=yyy] message`
*
* Tag and trace context are optional.
*/
function buildLogLine(
level: LogLevel,
message: string,
tag?: string,
traceCtx?: TraceContext | null,
): string {
const timestamp = new Date().toISOString();
const tagPart = tag ? ` [${tag}]` : '';
const tracePart = traceCtx
? ` [trace_id=${traceCtx.traceId} span_id=${traceCtx.spanId}]`
: '';
return `${timestamp} [${level}]${tagPart}${tracePart} ${message}\n`;
}
function writeLog(
session: DebugLogSession,
level: LogLevel,
tag: string | undefined,
args: unknown[],
): void {
if (!isDebugLogFileEnabled()) {
return;
}
const sessionId = session.getSessionId();
const logFilePath = Storage.getDebugLogPath(sessionId);
const message = formatArgs(args);
const traceCtx = getTraceContext();
const line = buildLogLine(level, message, tag, traceCtx);
void ensureDebugDirExists()
// Debug logs are best-effort diagnostic output: 1050+ call sites,
// default-enabled, fire-and-forget. Per-line fsync would force
// continuous I/O pressure / SSD wear without user benefit — losing
// the last few hundred ms of debug output on crash is acceptable
// and the module already tracks `hasWriteFailure` for the
// degraded-mode UI. Kernel page-cache flush is sufficient here.
// (JSONL session writes via writeLine/writeLineSync DO use
// flush:true — those are the actual closure target.)
.then(() => fs.appendFile(logFilePath, line, 'utf8'))
.catch(() => {
hasWriteFailure = true;
});
}
/**
* Returns true if any debug log write has failed.
* Used by the UI to show a degraded mode notice on startup.
*/
export function isDebugLoggingDegraded(): boolean {
return hasWriteFailure;
}
/**
* Resets the write failure tracking state.
* Primarily useful for testing.
*/
export function resetDebugLoggingState(): void {
hasWriteFailure = false;
ensureDebugDirPromise = null;
ensuredDebugDirPath = null;
}
const DEBUG_LATEST_ALIAS = 'latest';
const SESSION_ID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function updateLatestDebugLogAlias(sessionId: string): void {
if (!isDebugLogFileEnabled()) {
return;
}
if (!SESSION_ID_PATTERN.test(sessionId)) {
return;
}
const aliasPath = path.join(Storage.getGlobalDebugDir(), DEBUG_LATEST_ALIAS);
const targetPath = Storage.getDebugLogPath(sessionId);
void ensureDebugDirExists()
.then(() => updateSymlink(aliasPath, targetPath, { fallbackCopy: false }))
.catch(() => {
// Best-effort; don't degrade overall logging
});
}
/**
* Sets the process-wide debug log session used by createDebugLogger().
*
* This is the default session used when there is no async-local session bound
* via runWithDebugLogSession().
*/
export function setDebugLogSession(
session: DebugLogSession | null | undefined,
) {
globalSession = session ?? null;
if (session) {
updateLatestDebugLogAlias(session.getSessionId());
}
}
/**
* Runs a function with a session bound to the current async context.
*
* This is optional; createDebugLogger() falls back to the process-wide session
* set via setDebugLogSession().
*/
export function runWithDebugLogSession<T>(
session: DebugLogSession,
fn: () => T,
): T {
return sessionContext.run(session, fn);
}
export function runWithoutDebugLogSession<T>(fn: () => T): T {
return sessionContext.run(false, fn);
}
/**
* Creates a debug logger that writes to the current debug log session.
*
* Session resolution order:
* 1) async-local suppression or session
* 2) process-wide session (setDebugLogSession)
*/
export function createDebugLogger(tag?: string): DebugLogger {
return {
isEnabled: () => getActiveSession() !== null,
debug: (...args: unknown[]) => {
const session = getActiveSession();
if (!session) return;
writeLog(session, 'DEBUG', tag, args);
},
info: (...args: unknown[]) => {
const session = getActiveSession();
if (!session) return;
writeLog(session, 'INFO', tag, args);
},
warn: (...args: unknown[]) => {
const session = getActiveSession();
if (!session) return;
writeLog(session, 'WARN', tag, args);
},
error: (...args: unknown[]) => {
const session = getActiveSession();
if (!session) return;
writeLog(session, 'ERROR', tag, args);
},
};
}