-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlogger.ts
More file actions
381 lines (339 loc) · 11.5 KB
/
Copy pathlogger.ts
File metadata and controls
381 lines (339 loc) · 11.5 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* Enhanced Logger for structured and consistent logging
* Compatible with CommonJS and ESM environments
*/
/**
* Logger levels with their corresponding numeric values
*/
enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
NONE = 100
}
/**
* Configuration options for the Logger
*/
interface LoggerConfig {
level: LogLevel;
useTimestamp: boolean;
useColor: boolean;
logToFile?: string;
prettyPrint?: boolean;
}
/**
* When DOC2VEC_STRUCTURED_LOGS=1 (set by the controller when spawning sync jobs),
* every log line is emitted as a single JSON object so a parent process can parse
* the stream reliably. Human-formatted output is suppressed in this mode.
*/
const STRUCTURED = process.env.DOC2VEC_STRUCTURED_LOGS === '1';
function emitStructured(payload: Record<string, any>, useStderr = false): void {
const line = JSON.stringify(payload);
if (useStderr) {
process.stderr.write(line + '\n');
} else {
process.stdout.write(line + '\n');
}
}
function stringifyArg(arg: any): string {
if (arg instanceof Error) {
return `${arg.message}${arg.stack ? `\n${arg.stack}` : ''}`;
}
if (typeof arg === 'object' && arg !== null) {
try {
return JSON.stringify(arg);
} catch (e) {
return '[Unserializable Object]';
}
}
return String(arg);
}
/**
* Basic color functions that don't rely on external packages
*/
const colors = {
gray: (text: string) => `\x1b[90m${text}\x1b[0m`,
blue: (text: string) => `\x1b[34m${text}\x1b[0m`,
yellow: (text: string) => `\x1b[33m${text}\x1b[0m`,
red: (text: string) => `\x1b[31m${text}\x1b[0m`,
green: (text: string) => `\x1b[32m${text}\x1b[0m`,
reset: (text: string) => `\x1b[0m${text}\x1b[0m`
};
/**
* Enhanced Logger class with color-coding, timestamp, and formatting
*/
class Logger {
private config: LoggerConfig;
private moduleName: string;
/**
* Create a new Logger instance
*
* @param moduleName Name of the module using this logger
* @param config Logger configuration options
*/
constructor(moduleName: string, config?: Partial<LoggerConfig>) {
this.moduleName = moduleName;
this.config = {
level: LogLevel.INFO,
useTimestamp: true,
useColor: true,
prettyPrint: true,
...config
};
}
/**
* Format a log message with timestamp, level, and module information
*
* @param level Log level for this message
* @param message The message to log
* @param args Additional arguments to include
* @returns Formatted log message
*/
private formatMessage(level: string, message: string, args: any[] = []): string {
const timestamp = this.config.useTimestamp ?
`[${new Date().toISOString()}] ` : '';
const modulePrefix = this.moduleName ?
`[${this.moduleName}] ` : '';
const levelFormatted = `[${level.padEnd(5)}]`;
let formattedMessage = `${timestamp}${levelFormatted} ${modulePrefix}${message}`;
if (args.length > 0) {
const argsString = args.map(arg => {
if (arg instanceof Error) {
return `\n--- Error Details ---\nMessage: ${arg.message}\nStack:\n${arg.stack}\n--- End Error ---`;
}
else if (this.config.prettyPrint && typeof arg === 'object' && arg !== null) {
try {
return JSON.stringify(arg, null, 2);
} catch (e) {
return "[Unserializable Object]";
}
} else {
return String(arg);
}
}).join('\n');
if (this.config.prettyPrint) {
formattedMessage += `\n${argsString}`;
} else {
formattedMessage += ` ${args.map(String).join(' ')}`;
}
}
return formattedMessage;
}
/**
* Apply color to a message based on log level
*
* @param level Log level
* @param message Message to color
* @returns Colored message
*/
private colorize(level: LogLevel, message: string): string {
if (!this.config.useColor) return message;
switch (level) {
case LogLevel.DEBUG:
return colors.gray(message);
case LogLevel.INFO:
return colors.blue(message);
case LogLevel.WARN:
return colors.yellow(message);
case LogLevel.ERROR:
return colors.red(message);
default:
return message;
}
}
/**
* Log a debug message
*
* @param message Message to log
* @param args Additional arguments
*/
private emitJson(level: string, message: string, args: any[], useStderr = false): void {
const msg = args.length > 0
? `${message} ${args.map(stringifyArg).join(' ')}`
: message;
emitStructured({
ts: new Date().toISOString(),
level,
module: this.moduleName,
msg
}, useStderr);
}
debug(message: string, ...args: any[]): void {
if (this.config.level <= LogLevel.DEBUG) {
if (STRUCTURED) {
this.emitJson('debug', message, args);
return;
}
const formattedMessage = this.formatMessage('DEBUG', message, args);
console.log(this.colorize(LogLevel.DEBUG, formattedMessage));
}
}
/**
* Log an info message
*
* @param message Message to log
* @param args Additional arguments
*/
info(message: string, ...args: any[]): void {
if (this.config.level <= LogLevel.INFO) {
if (STRUCTURED) {
this.emitJson('info', message, args);
return;
}
const formattedMessage = this.formatMessage('INFO', message, args);
console.log(this.colorize(LogLevel.INFO, formattedMessage));
}
}
/**
* Log a warning message
*
* @param message Message to log
* @param args Additional arguments
*/
warn(message: string, ...args: any[]): void {
if (this.config.level <= LogLevel.WARN) {
if (STRUCTURED) {
this.emitJson('warn', message, args, true);
return;
}
const formattedMessage = this.formatMessage('WARN', message, args);
console.warn(this.colorize(LogLevel.WARN, formattedMessage));
}
}
/**
* Log an error message
*
* @param message Message to log
* @param args Additional arguments
*/
error(message: string, ...args: any[]): void {
if (this.config.level <= LogLevel.ERROR) {
if (STRUCTURED) {
this.emitJson('error', message, args, true);
return;
}
const formattedMessage = this.formatMessage('ERROR', message, args);
console.error(this.colorize(LogLevel.ERROR, formattedMessage));
}
}
/**
* Emit a structured event (e.g. run-summary). In structured mode this prints a
* machine-parseable JSON line; otherwise it logs the payload at info level.
*
* @param name Event name
* @param data Event payload
*/
event(name: string, data: Record<string, any> = {}): void {
if (STRUCTURED) {
emitStructured({ event: name, ts: new Date().toISOString(), ...data });
return;
}
this.info(`[event:${name}]`, data);
}
/**
* Create a child logger with a more specific module name
*
* @param subModule Name of the sub-module
* @returns New logger instance
*/
child(subModule: string): Logger {
return new Logger(`${this.moduleName}:${subModule}`, this.config);
}
/**
* Format a section header to clearly separate logical parts of execution
*
* @param title Section title
* @returns Logger instance for chaining
*/
section(title: string): Logger {
if (this.config.level <= LogLevel.INFO) {
if (STRUCTURED) {
emitStructured({ event: 'section', ts: new Date().toISOString(), module: this.moduleName, title });
return this;
}
const separator = '='.repeat(Math.max(80 - title.length - 4, 10));
const message = `${separator} ${title} ${separator}`;
console.log(this.colorize(LogLevel.INFO, message));
}
return this;
}
/**
* Create a progress indicator
*
* @param title Title of the operation
* @param total Total number of items to process
* @returns Object with update and complete methods
*/
progress(title: string, total: number) {
let current = 0;
const startTime = Date.now();
// In structured mode, throttle progress lines to at most one per second so a
// large crawl doesn't flood the parent process / database with log rows.
let lastStructuredEmit = 0;
const update = (increment = 1, message?: string) => {
if (this.config.level > LogLevel.INFO) return;
current += increment;
if (STRUCTURED) {
const now = Date.now();
if (now - lastStructuredEmit >= 1000 || current === total) {
lastStructuredEmit = now;
emitStructured({ event: 'progress', ts: new Date().toISOString(), module: this.moduleName, title, current, total, message });
}
return;
}
const percentage = Math.min(Math.floor((current / total) * 100), 100);
const elapsed = (Date.now() - startTime) / 1000;
let rate = current / elapsed;
let timeRemaining = '';
if (rate > 0 && current < total) {
const remainingSecs = (total - current) / rate;
timeRemaining = `, ETA: ${Math.floor(remainingSecs / 60)}m ${Math.floor(remainingSecs % 60)}s`;
}
const progressBar = this.createProgressBar(percentage);
const statusMsg = message ? ` - ${message}` : '';
console.log(this.colorize(
LogLevel.INFO,
this.formatMessage('INFO', `${title}: ${progressBar} ${percentage}% (${current}/${total}${timeRemaining})${statusMsg}`)
));
};
const complete = (message = 'Completed') => {
if (this.config.level > LogLevel.INFO) return;
const elapsed = (Date.now() - startTime) / 1000;
const rate = total / elapsed;
if (STRUCTURED) {
emitStructured({ event: 'progress', ts: new Date().toISOString(), module: this.moduleName, title, current: total, total, message: `${message} in ${elapsed.toFixed(2)}s`, done: true });
return;
}
console.log(this.colorize(
LogLevel.INFO,
this.formatMessage('INFO', `${title}: ${this.createProgressBar(100)} 100% (${total}/${total}) - ${message} in ${elapsed.toFixed(2)}s (${rate.toFixed(2)} items/sec)`)
));
};
return { update, complete };
}
/**
* Create a visual progress bar
*
* @param percentage Completion percentage
* @returns Visual progress bar
*/
private createProgressBar(percentage: number): string {
const width = 20;
const completeChars = Math.floor((percentage / 100) * width);
const incompleteChars = width - completeChars;
let bar = '[';
if (this.config.useColor) {
bar += colors.green('='.repeat(completeChars));
bar += ' '.repeat(incompleteChars);
} else {
bar += '='.repeat(completeChars);
bar += ' '.repeat(incompleteChars);
}
bar += ']';
return bar;
}
}
// Create a default logger instance
const defaultLogger = new Logger('app');
export { Logger, LogLevel, defaultLogger };