-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructured-logger.ts
More file actions
257 lines (228 loc) · 6.6 KB
/
Copy pathstructured-logger.ts
File metadata and controls
257 lines (228 loc) · 6.6 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
/**
* Structured logging with JSON support and correlation IDs
*/
import { randomBytes } from 'node:crypto';
export interface LogContext {
correlationId?: string;
requestId?: string;
userId?: string;
sessionId?: string;
traceId?: string;
spanId?: string;
[key: string]: unknown;
}
export interface LogEntry {
timestamp: string;
level: string;
message: string;
correlationId?: string;
component?: string;
context?: LogContext;
error?: {
name: string;
message: string;
stack?: string;
};
duration?: number;
[key: string]: unknown;
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export interface StructuredLoggerOptions {
format?: 'json' | 'text';
level?: LogLevel;
component?: string;
defaultContext?: LogContext;
output?: (_entry: LogEntry) => void;
}
/**
* Generate a unique correlation ID
*/
export function generateCorrelationId(): string {
return randomBytes(16).toString('hex');
}
/**
* Structured logger with JSON support
*/
export class StructuredLogger {
private readonly format: 'json' | 'text';
private readonly level: LogLevel;
private readonly component?: string;
private readonly defaultContext: LogContext;
private readonly output: (_entry: LogEntry) => void;
private readonly levelPriority: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
fatal: 4,
};
constructor(options: StructuredLoggerOptions = {}) {
this.format = options.format || 'text';
this.level = options.level || 'info';
this.component = options.component;
this.defaultContext = options.defaultContext || {};
this.output =
options.output ||
(entry => {
if (this.format === 'json') {
console.log(JSON.stringify(entry));
} else {
this.outputText(entry);
}
});
}
private outputText(entry: LogEntry): void {
const prefix = `[${entry.timestamp}] [${entry.level.toUpperCase()}]`;
const component = entry.component ? ` [${entry.component}]` : '';
const correlationId = entry.correlationId ? ` [${entry.correlationId}]` : '';
let message = `${prefix}${component}${correlationId} ${entry.message}`;
if (entry.context && Object.keys(entry.context).length > 0) {
const contextStr = Object.entries(entry.context)
.filter(([key]) => key !== 'correlationId')
.map(([key, value]) => `${key}=${JSON.stringify(value)}`)
.join(' ');
if (contextStr) {
message += ` ${contextStr}`;
}
}
if (entry.error) {
message += ` error=${entry.error.name}: ${entry.error.message}`;
if (entry.error.stack) {
message += `\n${entry.error.stack}`;
}
}
if (entry.duration !== undefined) {
message += ` duration=${entry.duration}ms`;
}
console.log(message);
}
private shouldLog(level: LogLevel): boolean {
return this.levelPriority[level] >= this.levelPriority[this.level];
}
private createEntry(
level: LogLevel,
message: string,
context?: LogContext,
error?: Error,
duration?: number
): LogEntry {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level,
message,
component: this.component,
};
// Merge contexts
const fullContext = { ...this.defaultContext, ...context };
if (Object.keys(fullContext).length > 0) {
entry.context = fullContext;
if (fullContext.correlationId) {
entry.correlationId = fullContext.correlationId;
}
}
if (error) {
entry.error = {
name: error.name,
message: error.message,
stack: error.stack,
};
}
if (duration !== undefined) {
entry.duration = duration;
}
return entry;
}
debug(message: string, context?: LogContext, duration?: number): void {
if (this.shouldLog('debug')) {
this.output(this.createEntry('debug', message, context, undefined, duration));
}
}
info(message: string, context?: LogContext, duration?: number): void {
if (this.shouldLog('info')) {
this.output(this.createEntry('info', message, context, undefined, duration));
}
}
warn(message: string, context?: LogContext, error?: Error, duration?: number): void {
if (this.shouldLog('warn')) {
this.output(this.createEntry('warn', message, context, error, duration));
}
}
error(message: string, error?: Error, context?: LogContext, duration?: number): void {
if (this.shouldLog('error')) {
this.output(this.createEntry('error', message, context, error, duration));
}
}
fatal(message: string, error?: Error, context?: LogContext): void {
if (this.shouldLog('fatal')) {
this.output(this.createEntry('fatal', message, context, error));
}
}
/**
* Create a child logger with additional context
*/
child(context: LogContext): StructuredLogger {
return new StructuredLogger({
format: this.format,
level: this.level,
component: this.component,
defaultContext: { ...this.defaultContext, ...context },
output: this.output,
});
}
/**
* Create a timer for measuring operation duration
*/
startTimer(): () => number {
const start = Date.now();
return () => Date.now() - start;
}
}
/**
* Global logger factory with structured logging support
*/
export class StructuredLoggerFactory {
private static readonly loggers = new Map<string, StructuredLogger>();
private static globalOptions: StructuredLoggerOptions = {
format: process.env.LOG_FORMAT === 'json' ? 'json' : 'text',
level: (process.env.LOG_LEVEL as LogLevel) || 'info',
};
/**
* Configure global logging options
*/
static configure(options: StructuredLoggerOptions): void {
this.globalOptions = { ...this.globalOptions, ...options };
// Update existing loggers
for (const [component] of this.loggers) {
this.loggers.set(
component,
new StructuredLogger({
...this.globalOptions,
component,
})
);
}
}
/**
* Get or create a logger for a component
*/
static getLogger(component?: string): StructuredLogger {
const key = component || 'default';
if (!this.loggers.has(key)) {
this.loggers.set(
key,
new StructuredLogger({
...this.globalOptions,
component,
})
);
}
return this.loggers.get(key)!;
}
/**
* Create a logger with correlation ID
*/
static getLoggerWithCorrelation(component?: string, correlationId?: string): StructuredLogger {
const id = correlationId || generateCorrelationId();
return this.getLogger(component).child({ correlationId: id });
}
}