Repository navigation
Expand file tree
/
Copy pathlogger.ts
More file actions
388 lines (345 loc) · 9.49 KB
/
Copy pathlogger.ts
File metadata and controls
388 lines (345 loc) · 9.49 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
382
383
384
385
386
387
388
/**
* Structured Logging Service
*
* Production-grade logging with structured output, log levels, and context propagation.
* Designed for cloud-native environments with JSON output for log aggregation systems.
*
* Security Assumptions:
* - PII and sensitive data must be explicitly redacted before logging
* - Log output should not contain credentials, tokens, or private keys
* - Error stack traces may contain sensitive paths in production
*
* @module lib/logger
*/
/**
* Standard log levels following RFC 5424 severity levels
*/
export enum LogLevel {
/** System is unusable */
EMERGENCY = 0,
/** Action must be taken immediately */
ALERT = 1,
/** Critical conditions */
CRITICAL = 2,
/** Error conditions */
ERROR = 3,
/** Warning conditions */
WARN = 4,
/** Normal but significant condition */
INFO = 5,
/** Informational messages */
DEBUG = 6,
/** Debug-level messages */
TRACE = 7,
}
/**
* Log level names for human-readable output
*/
const LOG_LEVEL_NAMES: Record<LogLevel, string> = {
[LogLevel.EMERGENCY]: 'EMERGENCY',
[LogLevel.ALERT]: 'ALERT',
[LogLevel.CRITICAL]: 'CRITICAL',
[LogLevel.ERROR]: 'ERROR',
[LogLevel.WARN]: 'WARN',
[LogLevel.INFO]: 'INFO',
[LogLevel.DEBUG]: 'DEBUG',
[LogLevel.TRACE]: 'TRACE',
};
/**
* Structured log entry
*/
export interface LogEntry {
/** ISO 8601 timestamp */
timestamp: string;
/** Log level */
level: string;
/** Log message */
message: string;
/** Request ID for correlation */
requestId?: string;
/** User ID for audit trail */
userId?: string;
/** Additional context data */
context?: Record<string, unknown>;
/** Error details if applicable */
error?: {
name: string;
message: string;
stack?: string;
};
/** Allow any additional properties from context */
[key: string]: unknown;
}
/**
* Logger configuration
*/
export interface LoggerConfig {
/** Minimum log level to output */
level: LogLevel;
/** Enable pretty-printing for development */
pretty: boolean;
/** Include stack traces in error logs */
includeStackTrace: boolean;
/** Service name for log identification */
serviceName: string;
}
/**
* Fields to redact from logs (case-insensitive)
*/
const SENSITIVE_FIELDS = [
'password',
'secret',
'token',
'apikey',
'api_key',
'authorization',
'cookie',
'session',
'private_key',
'privatekey',
'credit_card',
'creditcard',
'ssn',
'social_security',
];
/**
* Logger - Structured logging service with context propagation
*
* Provides structured JSON logging with automatic PII redaction and
* context propagation for distributed tracing.
*
* Usage:
* ```typescript
* const logger = new Logger({ level: LogLevel.INFO });
* logger.info('User logged in', { userId: '123', ip: '192.168.1.1' });
* logger.error('Database connection failed', { error: dbError });
* ```
*/
export class Logger {
private config: LoggerConfig;
private context: Record<string, unknown> = {};
constructor(config: Partial<LoggerConfig> = {}) {
this.config = {
level: config.level ?? this.getDefaultLogLevel(),
pretty: config.pretty ?? process.env.NODE_ENV !== 'production',
includeStackTrace: config.includeStackTrace ?? process.env.NODE_ENV !== 'production',
serviceName: config.serviceName ?? 'revora-backend',
};
}
/**
* Get default log level from environment
*/
private getDefaultLogLevel(): LogLevel {
const envLevel = process.env.LOG_LEVEL?.toUpperCase();
switch (envLevel) {
case 'EMERGENCY': return LogLevel.EMERGENCY;
case 'ALERT': return LogLevel.ALERT;
case 'CRITICAL': return LogLevel.CRITICAL;
case 'ERROR': return LogLevel.ERROR;
case 'WARN': return LogLevel.WARN;
case 'INFO': return LogLevel.INFO;
case 'DEBUG': return LogLevel.DEBUG;
case 'TRACE': return LogLevel.TRACE;
default: return process.env.NODE_ENV === 'production' ? LogLevel.INFO : LogLevel.DEBUG;
}
}
/**
* Set persistent context for all subsequent logs
* @param context Context data to merge
*/
setContext(context: Record<string, unknown>): void {
this.context = { ...this.context, ...context };
}
/**
* Clear persistent context
*/
clearContext(): void {
this.context = {};
}
/**
* Create a child logger with additional context
* @param context Additional context for child logger
* @returns New logger instance with merged context
*/
child(context: Record<string, unknown>): Logger {
const child = new Logger(this.config);
child.context = { ...this.context, ...context };
return child;
}
/**
* Redact sensitive fields from object
* @param obj Object to redact
* @returns Redacted object
*/
private redactSensitive(obj: unknown, seen = new WeakSet<object>()): unknown {
if (obj === null || obj === undefined) return obj;
if (typeof obj !== 'object') return obj;
if (obj instanceof Error) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => this.redactSensitive(item, seen));
}
if (seen.has(obj)) {
return '[Circular]';
}
seen.add(obj);
const redacted: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
const lowerKey = key.toLowerCase();
const isSensitive = SENSITIVE_FIELDS.some((field) => lowerKey.includes(field));
if (isSensitive) {
redacted[key] = '[REDACTED]';
} else if (typeof value === 'object' && value !== null) {
redacted[key] = this.redactSensitive(value, seen);
} else {
redacted[key] = value;
}
}
return redacted;
}
/**
* Format error for logging
* @param error Error object
* @returns Formatted error object
*/
private formatError(error: unknown): LogEntry['error'] {
if (error instanceof Error) {
return {
name: error.name,
message: error.message,
stack: this.config.includeStackTrace ? error.stack : undefined,
};
}
return {
name: 'UnknownError',
message: String(error),
};
}
/**
* Write log entry
* @param level Log level
* @param message Log message
* @param context Additional context
*/
private log(level: LogLevel, message: string, context?: Record<string, unknown>): void {
if (level > this.config.level) return;
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level: LOG_LEVEL_NAMES[level],
message,
...this.context,
};
if (context) {
const redacted = this.redactSensitive(context) as Record<string, unknown>;
// Extract special fields
if (redacted.requestId) {
entry.requestId = String(redacted.requestId);
delete redacted.requestId;
}
if (redacted.userId) {
entry.userId = String(redacted.userId);
delete redacted.userId;
}
if (redacted.error) {
entry.error = this.formatError(redacted.error);
delete redacted.error;
}
// Add remaining context
if (Object.keys(redacted).length > 0) {
entry.context = redacted;
}
}
const output = this.config.pretty ? this.prettyFormat(entry) : JSON.stringify(entry);
// Route to appropriate console method
if (level <= LogLevel.ERROR) {
console.error(output);
} else if (level === LogLevel.WARN) {
console.warn(output);
} else {
console.log(output);
}
}
/**
* Pretty-print log entry for development
* @param entry Log entry
* @returns Formatted string
*/
private prettyFormat(entry: LogEntry): string {
const parts = [
entry.timestamp,
`[${entry.level}]`,
entry.message,
];
if (entry.requestId) {
parts.push(`(req: ${entry.requestId})`);
}
if (entry.userId) {
parts.push(`(user: ${entry.userId})`);
}
if (entry.context) {
parts.push(JSON.stringify(entry.context));
}
if (entry.error) {
parts.push(`\nError: ${entry.error.name}: ${entry.error.message}`);
if (entry.error.stack) {
parts.push(`\n${entry.error.stack}`);
}
}
return parts.join(' ');
}
/**
* Log emergency message
*/
emergency(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.EMERGENCY, message, context);
}
/**
* Log alert message
*/
alert(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.ALERT, message, context);
}
/**
* Log critical message
*/
critical(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.CRITICAL, message, context);
}
/**
* Log error message
*/
error(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.ERROR, message, context);
}
/**
* Log warning message
*/
warn(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.WARN, message, context);
}
/**
* Log info message
*/
info(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.INFO, message, context);
}
/**
* Log debug message
*/
debug(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.DEBUG, message, context);
}
/**
* Log trace message
*/
trace(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.TRACE, message, context);
}
}
/**
* Global logger instance
* Singleton pattern for application-wide logging
*/
export const globalLogger = new Logger();
export const logger = globalLogger;