@asaidimu/utils-logger 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +267 -0
- package/index.d.mts +334 -0
- package/index.d.ts +334 -0
- package/index.js +1 -0
- package/index.mjs +1 -0
- package/package.json +69 -0
package/index.d.ts
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Represents the severity level of a system log entry.
|
|
5
|
+
* Levels are ordered by increasing severity: trace, debug, info, warn, error.
|
|
6
|
+
*/
|
|
7
|
+
type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
|
|
8
|
+
/**
|
|
9
|
+
* Defines a destination where system logs are outputted or processed.
|
|
10
|
+
* Custom sinks (e.g., File, Logstash, Sentry) must implement this interface.
|
|
11
|
+
*/
|
|
12
|
+
interface LogSink {
|
|
13
|
+
/**
|
|
14
|
+
* Dispatches a structured log entry to the underlying destination.
|
|
15
|
+
*
|
|
16
|
+
* @param record - The complete log object containing metadata and payload.
|
|
17
|
+
* @returns A void or Promise that resolves when the log has been safely handed off.
|
|
18
|
+
*/
|
|
19
|
+
write(record: SystemLog): void | Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Structure representing a fully contextualized system log entry ready for sinking.
|
|
23
|
+
*/
|
|
24
|
+
interface SystemLog {
|
|
25
|
+
/** The severity level of the log. */
|
|
26
|
+
level: LogLevel;
|
|
27
|
+
/** A clear, human-readable string identifying the distinct event (e.g., "user_login_failed"). */
|
|
28
|
+
event: string;
|
|
29
|
+
/** Additional structured data specific to this log instantiation. */
|
|
30
|
+
data?: object;
|
|
31
|
+
/** Contextual data shared across the logger instance (e.g., traceIds, environment). */
|
|
32
|
+
context?: object;
|
|
33
|
+
/** Epoch timestamp in milliseconds denoting when the log event occurred. */
|
|
34
|
+
timestamp: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Primary logger interface providing level-specific log dispatching and context-chaining.
|
|
38
|
+
*/
|
|
39
|
+
interface SystemLogger {
|
|
40
|
+
/** Logs high-volume, extremely fine-grained diagnostic details. */
|
|
41
|
+
trace(event: string, data?: object): void;
|
|
42
|
+
/** Logs diagnostic information useful during local development or debugging. */
|
|
43
|
+
debug(event: string, data?: object): void;
|
|
44
|
+
/** Logs standard operational events that track the healthy flow of the system. */
|
|
45
|
+
info(event: string, data?: object): void;
|
|
46
|
+
/** Alias for the `info` logging method. */
|
|
47
|
+
log(event: string, data?: object): void;
|
|
48
|
+
/** Logs non-fatal operational anomalies or conditions that deserve attention. */
|
|
49
|
+
warn(event: string, data?: object): void;
|
|
50
|
+
/** Logs critical errors, failures, or exceptions preventing a transaction/process. */
|
|
51
|
+
error(event: string, data?: unknown): void;
|
|
52
|
+
/**
|
|
53
|
+
* Directly forwards a pre-constructed `SystemLog` record through the logger's pipeline.
|
|
54
|
+
* Combines instance context before outputting.
|
|
55
|
+
*/
|
|
56
|
+
write(record: SystemLog): void;
|
|
57
|
+
/**
|
|
58
|
+
* Generates a new `SystemLogger` instance that shares the existing sinks and parent
|
|
59
|
+
* context, deeply merging the newly provided context on top.
|
|
60
|
+
*
|
|
61
|
+
* @param context - The metadata to append to all subsequent logs emitted by the child logger.
|
|
62
|
+
*/
|
|
63
|
+
child(context: object): SystemLogger;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Numeric priority weights mapping to `LogLevel` values.
|
|
67
|
+
* Useful for filtering logs below a specific severity threshold.
|
|
68
|
+
*/
|
|
69
|
+
declare const LogLevelPriority: Record<LogLevel, number>;
|
|
70
|
+
/**
|
|
71
|
+
* Concrete implementation of the `SystemLogger` interface.
|
|
72
|
+
* Handles active context-aggregation, standardized formatting of localized error payloads,
|
|
73
|
+
* and safe dispatch handling for downstream sinks.
|
|
74
|
+
*/
|
|
75
|
+
declare class Logger implements SystemLogger {
|
|
76
|
+
private context;
|
|
77
|
+
private sink;
|
|
78
|
+
/**
|
|
79
|
+
* Initializes a new instance of the core Logger wrapper.
|
|
80
|
+
* * @param sinks - An array of outputs where logs generated by this instance will be sent.
|
|
81
|
+
* @param context - Base contextual metadata to affix across all downstream log events.
|
|
82
|
+
*/
|
|
83
|
+
constructor(sinks: Array<LogSink>, context?: object);
|
|
84
|
+
/**
|
|
85
|
+
* Safely updates or assigns the core logging sink.
|
|
86
|
+
* Used internally to re-attach existing sink structures to spawned child logger instances.
|
|
87
|
+
*/
|
|
88
|
+
private setSink;
|
|
89
|
+
/**
|
|
90
|
+
* Extracts structural tracking fields from standard JavaScript errors and advanced domain `SystemError` objects.
|
|
91
|
+
* Ensures call-stacks and metadata parameters map clean object parameters without blowing up standard logging pipelines.
|
|
92
|
+
* * @param err - The Error object or descendant instance to format.
|
|
93
|
+
* @returns An object payload mapped under standard keys ready for insertion into a log.
|
|
94
|
+
*/
|
|
95
|
+
private extractErrorData;
|
|
96
|
+
/**
|
|
97
|
+
* Core dispatcher compiling standard schema variables, timestamps, contexts,
|
|
98
|
+
* and payloads prior to writing to the underlying `LogSink`.
|
|
99
|
+
* * @internal
|
|
100
|
+
*/
|
|
101
|
+
private emit;
|
|
102
|
+
trace(event: string, data?: object): void;
|
|
103
|
+
debug(event: string, data?: object): void;
|
|
104
|
+
info(event: string, data?: object): void;
|
|
105
|
+
log(event: string, data?: object): void;
|
|
106
|
+
warn(event: string, data?: object): void;
|
|
107
|
+
error(event: string, data?: unknown): void;
|
|
108
|
+
/**
|
|
109
|
+
* Writes an externally built log record into the logging framework sink.
|
|
110
|
+
* Merges local logger metadata onto incoming payloads with priority leaning toward overriding parameters.
|
|
111
|
+
*/
|
|
112
|
+
write(record: SystemLog): void;
|
|
113
|
+
/**
|
|
114
|
+
* Spawns a child logger instance carrying over pre-defined context parameters.
|
|
115
|
+
* Context configurations defined down-stream overwrite conflicting identifiers.
|
|
116
|
+
*/
|
|
117
|
+
child(context: object): SystemLogger;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Standard system descriptor streams for console outputs. */
|
|
121
|
+
type ConsolePipe = "stdout" | "stderr";
|
|
122
|
+
/** Configuration options modifying behavior of the `ConsoleSink`. */
|
|
123
|
+
interface ConsoleSinkOptions {
|
|
124
|
+
/** Optional override mapping log levels to specific output pipes (`stdout` or `stderr`). */
|
|
125
|
+
pipeMap?: Partial<Record<LogLevel, ConsolePipe>>;
|
|
126
|
+
/** Custom transformation callback converting a `SystemLog` payload into a printable string string. */
|
|
127
|
+
format?: (record: SystemLog) => string;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* A `LogSink` implementation that writes formatted log strings to terminal stdout/stderr channels.
|
|
131
|
+
* Automatically switches between runtime capabilities (Node.js `process.stdout` or generic global `console`).
|
|
132
|
+
*/
|
|
133
|
+
declare class ConsoleSink implements LogSink {
|
|
134
|
+
private pipeMap;
|
|
135
|
+
private format;
|
|
136
|
+
/**
|
|
137
|
+
* Initializes a new instance of the `ConsoleSink`.
|
|
138
|
+
* * @param options - Configuration definitions for custom formats and piping targets.
|
|
139
|
+
*/
|
|
140
|
+
constructor(options?: ConsoleSinkOptions);
|
|
141
|
+
/**
|
|
142
|
+
* Processes a log record and flushes it immediately to the runtime stream.
|
|
143
|
+
* Non-stringifiable context or data entries will fallback to standard JSON representations.
|
|
144
|
+
*/
|
|
145
|
+
write(record: SystemLog): void;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Interface defining the shape of the EventBus.
|
|
150
|
+
* @template TEventMap - A record mapping event names to their respective payload types.
|
|
151
|
+
*/
|
|
152
|
+
interface EventBus<TEventMap extends Record<string, any>> {
|
|
153
|
+
/**
|
|
154
|
+
* Subscribes to a specific event by name.
|
|
155
|
+
* @param eventName - The name of the event to subscribe to.
|
|
156
|
+
* @param callback - The function to call when the event is emitted.
|
|
157
|
+
* @param options - Extra options to determine the behaviour of the
|
|
158
|
+
* subscription
|
|
159
|
+
* @returns A function to unsubscribe from the event.
|
|
160
|
+
*/
|
|
161
|
+
subscribe: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions) => () => void;
|
|
162
|
+
/**
|
|
163
|
+
* Subscribes to an event and automatically unsubscribes after it fires once.
|
|
164
|
+
* @param eventName - The name of the event to subscribe to.
|
|
165
|
+
* @param callback - The function to call when the event is emitted.
|
|
166
|
+
* @returns A function to cancel the one-shot subscription before it fires.
|
|
167
|
+
*/
|
|
168
|
+
once: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions) => () => void;
|
|
169
|
+
/**
|
|
170
|
+
* Emits an event with a payload to all subscribed listeners.
|
|
171
|
+
* @param event - An object containing the event name and payload.
|
|
172
|
+
*/
|
|
173
|
+
emit: <TEventName extends keyof TEventMap>(event: {
|
|
174
|
+
name: TEventName;
|
|
175
|
+
payload: TEventMap[TEventName];
|
|
176
|
+
}) => void;
|
|
177
|
+
/**
|
|
178
|
+
* Retrieves metrics about event bus usage.
|
|
179
|
+
* @returns An object containing various metrics.
|
|
180
|
+
*/
|
|
181
|
+
metrics: () => EventMetrics;
|
|
182
|
+
/**
|
|
183
|
+
* Clears all subscriptions and resets metrics.
|
|
184
|
+
*
|
|
185
|
+
* After calling `clear()`, the bus is fully reset and can be reused
|
|
186
|
+
* cross-tab communication is re-established if it was previously enabled.
|
|
187
|
+
*
|
|
188
|
+
* @param options - Optional configuration object.
|
|
189
|
+
* @param options.permanent - If `true`, the bus becomes permanently unusable after clearing.
|
|
190
|
+
* Defaults to `false`.
|
|
191
|
+
* @returns {void}
|
|
192
|
+
*/
|
|
193
|
+
clear: (options?: {
|
|
194
|
+
permanent?: boolean;
|
|
195
|
+
}) => void;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Interface defining the metrics tracked by the EventBus.
|
|
199
|
+
*/
|
|
200
|
+
interface EventMetrics {
|
|
201
|
+
/** Total number of events emitted (both sync and deferred paths). */
|
|
202
|
+
totalEvents: number;
|
|
203
|
+
/** Number of active subscriptions across all event names. */
|
|
204
|
+
activeSubscriptions: number;
|
|
205
|
+
/** Map of event names to their emission counts. */
|
|
206
|
+
eventCounts: Map<string, number>;
|
|
207
|
+
/** Average duration of event dispatch in milliseconds. */
|
|
208
|
+
averageEmitDuration: number;
|
|
209
|
+
}
|
|
210
|
+
interface SubscribeOptions {
|
|
211
|
+
/**
|
|
212
|
+
* Debounce delay in milliseconds. When multiple events arrive in quick
|
|
213
|
+
* succession, the callback runs only after the quiet period ends, using the
|
|
214
|
+
* latest payload. Default = no debouncing.
|
|
215
|
+
*/
|
|
216
|
+
debounce?: number;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Configuration options for the EventBusSink when routing all logs to a single,
|
|
221
|
+
* static event channel on the EventBus.
|
|
222
|
+
*/
|
|
223
|
+
interface StaticRouteOptions<TEventMap extends Record<string, any>, TEventName extends keyof TEventMap> {
|
|
224
|
+
/** The fixed event name on the bus where all logs will be published. */
|
|
225
|
+
event: TEventName;
|
|
226
|
+
/** * Transforms the `SystemLog` into the format expected by the target event's payload.
|
|
227
|
+
* If omitted, the raw `SystemLog` is passed (requires type compatibility).
|
|
228
|
+
*/
|
|
229
|
+
map?: (record: SystemLog) => TEventMap[TEventName];
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Configuration options for the EventBusSink when routing logs dynamically
|
|
233
|
+
* across various event channels based on log record properties.
|
|
234
|
+
*/
|
|
235
|
+
interface DynamicRouteOptions<TEventMap extends Record<string, any>> {
|
|
236
|
+
/** A resolver callback that determines which event channel on the bus to target for a given log. */
|
|
237
|
+
resolve: (record: SystemLog) => keyof TEventMap;
|
|
238
|
+
/** * Transforms the `SystemLog` into the payload format expected by the resolved event channel.
|
|
239
|
+
* If omitted, the raw `SystemLog` is forwarded.
|
|
240
|
+
*/
|
|
241
|
+
map?: (record: SystemLog, eventName: keyof TEventMap) => TEventMap[keyof TEventMap];
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* A `LogSink` implementation that translates and forwards `SystemLog` records
|
|
245
|
+
* into an application-wide or cross-tab `EventBus`.
|
|
246
|
+
* * @template TEventMap - The schema defining available event names and payloads on the target bus.
|
|
247
|
+
*/
|
|
248
|
+
declare class EventBusSink<TEventMap extends Record<string, any>> implements LogSink {
|
|
249
|
+
private eventBus;
|
|
250
|
+
private resolveEventName;
|
|
251
|
+
private mapPayload;
|
|
252
|
+
/**
|
|
253
|
+
* Initializes the EventBusSink using a static event channel definition.
|
|
254
|
+
*/
|
|
255
|
+
constructor(eventBus: EventBus<TEventMap>, options: StaticRouteOptions<TEventMap, keyof TEventMap>);
|
|
256
|
+
/**
|
|
257
|
+
* Initializes the EventBusSink using a dynamic event resolution function.
|
|
258
|
+
*/
|
|
259
|
+
constructor(eventBus: EventBus<TEventMap>, options: DynamicRouteOptions<TEventMap>);
|
|
260
|
+
/**
|
|
261
|
+
* Dispatches the incoming system log to the configured EventBus channel.
|
|
262
|
+
* Wraps operations in a guard block to ensure event bus payload mapping anomalies
|
|
263
|
+
* or downstream listener execution crashes do not disrupt the critical logger pathway.
|
|
264
|
+
* * @param record - The structural log entry processed by the parent logger.
|
|
265
|
+
*/
|
|
266
|
+
write(record: SystemLog): void;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
type FuzzEventRegistry = Record<LogLevel, string[]>;
|
|
270
|
+
interface FakerFuzzOptions {
|
|
271
|
+
minIntervalMs?: number;
|
|
272
|
+
maxIntervalMs?: number;
|
|
273
|
+
allowedLevels?: LogLevel[];
|
|
274
|
+
eventRegistry?: Partial<FuzzEventRegistry>;
|
|
275
|
+
}
|
|
276
|
+
declare class Fuzz {
|
|
277
|
+
private logger;
|
|
278
|
+
private minIntervalMs;
|
|
279
|
+
private maxIntervalMs;
|
|
280
|
+
private allowedLevels;
|
|
281
|
+
private eventRegistry;
|
|
282
|
+
private timer;
|
|
283
|
+
private isRunning;
|
|
284
|
+
constructor(targetLogger: SystemLogger, options?: FakerFuzzOptions);
|
|
285
|
+
start(): void;
|
|
286
|
+
stop(): void;
|
|
287
|
+
private scheduleNextTick;
|
|
288
|
+
private getEventName;
|
|
289
|
+
private emitRandomLog;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Configuration options for the UnsecureWebSocketServerSink.
|
|
294
|
+
*/
|
|
295
|
+
interface UnsecureWebSocketSinkOptions {
|
|
296
|
+
/**
|
|
297
|
+
* An optional filter function to determine if a log should be broadcasted.
|
|
298
|
+
*/
|
|
299
|
+
filter?: (record: SystemLog) => boolean;
|
|
300
|
+
/**
|
|
301
|
+
* Custom serialization function to transform the log before wire transmission.
|
|
302
|
+
* Defaults to standard `JSON.stringify`.
|
|
303
|
+
*/
|
|
304
|
+
serialize?: (record: SystemLog) => string;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* A `LogSink` implementation that broadcasts structured system logs in real-time
|
|
308
|
+
* to all connected WebSocket clients without verifying credentials.
|
|
309
|
+
* * @deprecated **SECURITY WARNING:** This sink performs no authentication or token validation.
|
|
310
|
+
* Do not expose this server to the public internet. Use exclusively for local development
|
|
311
|
+
* or behind heavily isolated VPC/internal network infrastructure.
|
|
312
|
+
*/
|
|
313
|
+
declare class UnsecureWebSocketServerSink implements LogSink {
|
|
314
|
+
private wss;
|
|
315
|
+
private filter?;
|
|
316
|
+
private serialize;
|
|
317
|
+
/**
|
|
318
|
+
* @param wss - An instantiated and running WebSocketServer instance.
|
|
319
|
+
* @param options - Configuration options for filtering and formatting the socket stream.
|
|
320
|
+
*/
|
|
321
|
+
constructor(wss: WebSocketServer, options?: UnsecureWebSocketSinkOptions);
|
|
322
|
+
/**
|
|
323
|
+
* Broadcasts the incoming system log to all open, unauthenticated WebSocket clients.
|
|
324
|
+
* * @param record - The structural log entry processed by the parent logger.
|
|
325
|
+
*/
|
|
326
|
+
write(record: SystemLog): void;
|
|
327
|
+
private handleClientError;
|
|
328
|
+
/**
|
|
329
|
+
* Periodically checks for and prunes "ghost" connections.
|
|
330
|
+
*/
|
|
331
|
+
private initializeHeartbeat;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export { type ConsolePipe, ConsoleSink, type ConsoleSinkOptions, type DynamicRouteOptions, EventBusSink, type FakerFuzzOptions, Fuzz, type FuzzEventRegistry, type LogLevel, LogLevelPriority, type LogSink, Logger, type StaticRouteOptions, type SystemLog, type SystemLogger, UnsecureWebSocketServerSink, type UnsecureWebSocketSinkOptions };
|