-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogger.ts
287 lines (252 loc) · 8.45 KB
/
logger.ts
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
/**
* 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;
}
/**
* 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
*/
debug(message: string, ...args: any[]): void {
if (this.config.level <= LogLevel.DEBUG) {
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) {
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) {
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) {
const formattedMessage = this.formatMessage('ERROR', message, args);
console.error(this.colorize(LogLevel.ERROR, formattedMessage));
}
}
/**
* 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) {
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();
const update = (increment = 1, message?: string) => {
if (this.config.level > LogLevel.INFO) return;
current += increment;
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;
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 };