@rabbit-company/logger 4.0.0 → 5.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.
@@ -1,513 +1,343 @@
1
1
  /**
2
- * Namespace for logging utility functions and configurations.
2
+ * Enum representing various text colors for terminal output using ANSI escape codes.
3
+ * @readonly
3
4
  */
4
- declare namespace Logger {
5
+ export declare const enum Colors {
6
+ /** Reset all attributes (color, bold, etc.) to default. */
7
+ RESET = "\u001B[0m",
8
+ /** Apply bold text formatting. */
9
+ BOLD = "\u001B[1m",
10
+ /** Black text color. */
11
+ BLACK = "\u001B[30m",
12
+ /** Red text color. */
13
+ RED = "\u001B[31m",
14
+ /** Green text color. */
15
+ GREEN = "\u001B[32m",
16
+ /** Yellow text color. */
17
+ YELLOW = "\u001B[33m",
18
+ /** Blue text color. */
19
+ BLUE = "\u001B[34m",
20
+ /** Magenta text color. */
21
+ MAGENTA = "\u001B[35m",
22
+ /** Cyan text color. */
23
+ CYAN = "\u001B[36m",
24
+ /** White text color. */
25
+ WHITE = "\u001B[37m",
26
+ /** Bright black (gray) text color. */
27
+ BRIGHT_BLACK = "\u001B[90m",
28
+ /** Bright red text color. */
29
+ BRIGHT_RED = "\u001B[91m",
30
+ /** Bright green text color. */
31
+ BRIGHT_GREEN = "\u001B[92m",
32
+ /** Bright yellow text color. */
33
+ BRIGHT_YELLOW = "\u001B[93m",
34
+ /** Bright blue text color. */
35
+ BRIGHT_BLUE = "\u001B[94m",
36
+ /** Bright magenta text color. */
37
+ BRIGHT_MAGENTA = "\u001B[95m",
38
+ /** Bright cyan text color. */
39
+ BRIGHT_CYAN = "\u001B[96m",
40
+ /** Bright white text color. */
41
+ BRIGHT_WHITE = "\u001B[97m"
42
+ }
43
+ /**
44
+ * Enum representing the various logging levels for filtering log messages.
45
+ *
46
+ * The levels are ordered from most important (ERROR) to least important (SILLY).
47
+ * When setting a log level, only messages of that level or higher will be emitted.
48
+ */
49
+ export declare enum Levels {
50
+ /**
51
+ * Error level. Indicates critical issues that require immediate attention.
52
+ * Use for unrecoverable errors that prevent normal operation.
53
+ */
54
+ ERROR = 0,
55
+ /**
56
+ * Warning level. Indicates potential issues or noteworthy conditions.
57
+ * Use for recoverable issues that don't prevent normal operation.
58
+ */
59
+ WARN = 1,
5
60
  /**
6
- * Enum representing various text colors for terminal output using ANSI escape codes.
7
- * @readonly
61
+ * Informational level. Provides general information about the application's state.
62
+ * Use for normal operational messages that highlight progress.
8
63
  */
9
- const enum Colors {
10
- /** Reset all attributes (color, bold, etc.) to default. */
11
- RESET = "\u001B[0m",
12
- /** Apply bold text formatting. */
13
- BOLD = "\u001B[1m",
14
- /** Black text color. */
15
- BLACK = "\u001B[30m",
16
- /** Red text color. */
17
- RED = "\u001B[31m",
18
- /** Green text color. */
19
- GREEN = "\u001B[32m",
20
- /** Yellow text color. */
21
- YELLOW = "\u001B[33m",
22
- /** Blue text color. */
23
- BLUE = "\u001B[34m",
24
- /** Magenta text color. */
25
- MAGENTA = "\u001B[35m",
26
- /** Cyan text color. */
27
- CYAN = "\u001B[36m",
28
- /** White text color. */
29
- WHITE = "\u001B[37m",
30
- /** Bright black (gray) text color. */
31
- BRIGHT_BLACK = "\u001B[90m",
32
- /** Bright red text color. */
33
- BRIGHT_RED = "\u001B[91m",
34
- /** Bright green text color. */
35
- BRIGHT_GREEN = "\u001B[92m",
36
- /** Bright yellow text color. */
37
- BRIGHT_YELLOW = "\u001B[93m",
38
- /** Bright blue text color. */
39
- BRIGHT_BLUE = "\u001B[94m",
40
- /** Bright magenta text color. */
41
- BRIGHT_MAGENTA = "\u001B[95m",
42
- /** Bright cyan text color. */
43
- BRIGHT_CYAN = "\u001B[96m",
44
- /** Bright white text color. */
45
- BRIGHT_WHITE = "\u001B[97m"
46
- }
64
+ INFO = 2,
47
65
  /**
48
- * Enum representing the various logging levels for filtering log messages.
49
- *
50
- * This enumeration defines different levels of logging severity, which can be used to control the verbosity of log
51
- * output. Each level represents a different degree of importance or detail, allowing for granular control over which
52
- * messages are logged based on their severity.
53
- *
54
- * **Logging Levels**:
55
- * - `ERROR`: Represents error messages that indicate significant issues that need immediate attention.
56
- * - `WARN`: Represents warning messages that indicate potential issues or noteworthy conditions that are not critical.
57
- * - `INFO`: Represents informational messages that provide general information about the application's operation.
58
- * - `HTTP`: Represents log messages related to HTTP requests and responses, useful for monitoring web traffic.
59
- * - `VERBOSE`: Represents detailed messages that include extensive information, typically used for in-depth debugging.
60
- * - `DEBUG`: Represents debugging messages that provide detailed context for troubleshooting and debugging purposes.
61
- * - `SILLY`: Represents very low-level messages used for detailed internal state logging or humorous messages.
62
- *
63
- * Each level corresponds to a specific degree of logging detail, allowing users to filter out less important messages
64
- * based on their needs.
65
- *
66
- * @readonly
67
- * @enum {number}
66
+ * HTTP-related level. Logs HTTP requests and responses.
67
+ * Use for tracking HTTP API calls and their status.
68
68
  */
69
- enum Levels {
70
- /** Error level. Indicates critical issues that require immediate attention. */
71
- ERROR = 0,
72
- /** Warning level. Indicates potential issues or noteworthy conditions. */
73
- WARN = 1,
74
- /** Informational level. Provides general information about the application's state. */
75
- INFO = 2,
76
- /** HTTP-related level. Logs HTTP requests and responses. */
77
- HTTP = 3,
78
- /** Verbose level. Provides detailed information for in-depth analysis. */
79
- VERBOSE = 4,
80
- /** Debug level. Provides detailed context for debugging purposes. */
81
- DEBUG = 5,
82
- /** Silly level. Logs very low-level or whimsical messages. */
83
- SILLY = 6
84
- }
69
+ HTTP = 3,
85
70
  /**
86
- * Maps logging levels to their corresponding colors.
87
- * Each level is associated with a specific color to visually distinguish log messages based on their severity.
88
- * This mapping allows for customization of log message appearance in the terminal by changing the color for each log level.
89
- *
90
- * Example:
91
- * To change the color of the `ERROR` log level to bright red and the `INFO` log level to bright green, you can modify the `LevelColors` object like this:
92
- *
93
- * ```typescript
94
- * LevelColors[Levels.ERROR] = Colors.BRIGHT_RED; // Change ERROR level color to bright red
95
- * LevelColors[Levels.INFO] = Colors.BRIGHT_GREEN; // Change INFO level color to bright green
96
- * ```
97
- *
98
- * The above example will result in `ERROR` messages being displayed in bright red and `INFO` messages in bright green in the terminal.
99
- *
100
- * @type {Record<Levels, Colors>}
71
+ * Verbose level. Provides detailed information for in-depth analysis.
72
+ * Use for detailed operational logs that are typically only needed during debugging.
101
73
  */
102
- let LevelColors: Record<Levels, Colors>;
74
+ VERBOSE = 4,
103
75
  /**
104
- * Indicates whether NDJson (Newline Delimited JSON) format is enabled for logging.
105
- *
106
- * When `NDJson` is set to `true`, log messages will be formatted as NDJson and stored internally. This enables you to retrieve
107
- * the logs in NDJson format using the `getNDJson()` function. The console output will remain in the standard log format regardless
108
- * of this setting. NDJson format is useful for structured logging and integration with log management systems that process JSON data.
109
- *
110
- * When `NDJson` is set to `false`, NDJson formatting is not applied, and no NDJson formatted logs will be stored.
111
- * The console output will still follow the configured format.
112
- *
113
- * Example:
114
- * To enable NDJson logging and store log messages in NDJson format:
115
- *
116
- * ```typescript
117
- * Logger.NDJson = true;
118
- * ```
119
- *
120
- * To retrieve NDJson formatted logs:
121
- *
122
- * ```typescript
123
- * const ndjsonLogs = Logger.getNDJson();
124
- * ```
125
- *
126
- * To disable NDJson logging:
127
- *
128
- * ```typescript
129
- * Logger.NDJson = false;
130
- * ```
131
- *
132
- * @type {boolean}
133
- * @default false
76
+ * Debug level. Provides detailed context for debugging purposes.
77
+ * Use for extended debugging information during development.
134
78
  */
135
- let NDJson: boolean;
79
+ DEBUG = 5,
136
80
  /**
137
- * Represents the current logging level that filters which messages are logged.
138
- *
139
- * Log messages with a level equal to or lower than this value will be output. Messages with a level higher than this value will be ignored.
140
- * This property allows you to control the verbosity of the logs, ensuring that only relevant log messages are captured based on the set threshold.
141
- *
142
- * Example:
143
- * To set the logging level to `SILLY`, which will log messages at all levels including `SILLY`, `DEBUG`, `VERBOSE`, `HTTP`, `INFO`, `WARN`, and `ERROR`, use:
144
- *
145
- * ```typescript
146
- * Logger.level = Levels.SILLY;
147
- * ```
148
- *
149
- * Setting the level to `INFO` will exclude `SILLY`,`DEBUG`, `VERBOSE` and `HTTP` messages and only show `INFO`, `WARN`, and `ERROR` messages:
150
- *
151
- * ```typescript
152
- * Logger.level = Levels.INFO;
153
- * ```
154
- *
155
- * @type {Levels}
156
- * @default Levels.INFO
81
+ * Silly level. Logs very low-level messages.
82
+ * Use for extremely verbose logging messages.
157
83
  */
158
- let level: Levels;
84
+ SILLY = 6
85
+ }
86
+ /**
87
+ * Represents a single log entry with message, severity level, timestamp, and optional metadata
88
+ */
89
+ export interface LogEntry {
90
+ /** The log message content */
91
+ message: string;
92
+ /** Severity level of the log entry */
93
+ level: Levels;
94
+ /** Timestamp in milliseconds since epoch */
95
+ timestamp: number;
96
+ /** Optional structured metadata associated with the log */
97
+ metadata?: Record<string, any>;
98
+ }
99
+ /**
100
+ * Interface for log transport implementations
101
+ */
102
+ export interface Transport {
103
+ /**
104
+ * Processes and outputs a log entry
105
+ * @param entry The log entry to process
106
+ */
107
+ log: (entry: LogEntry) => void;
108
+ }
109
+ /**
110
+ * Configuration options for the Logger instance
111
+ */
112
+ export interface LoggerConfig {
113
+ /** Minimum log level to output (default: INFO) */
114
+ level?: Levels;
115
+ /** Enable colored output (default: true) */
116
+ colors?: boolean;
117
+ /** Format string using {date}, {type}, {message} placeholders (default: "[{date}] {type} {message}") */
118
+ format?: string;
119
+ /** Array of transports to use (default: [ConsoleTransport]) */
120
+ transports?: Transport[];
121
+ }
122
+ /**
123
+ * Configuration for Loki transport
124
+ */
125
+ export interface LokiConfig {
126
+ /** Loki server URL (e.g., "http://localhost:3100") */
127
+ url: string;
128
+ /** Base labels to attach to all logs */
129
+ labels?: Record<string, string>;
130
+ /** Basic authentication credentials */
131
+ basicAuth?: {
132
+ username: string;
133
+ password: string;
134
+ };
135
+ /** Number of logs to batch before sending (default: 10) */
136
+ batchSize?: number;
137
+ /** Maximum time in ms to wait before sending a batch (default: 5000) */
138
+ batchTimeout?: number;
139
+ /** Tenant ID for multi-tenant Loki setups */
140
+ tenantID?: string;
141
+ /** Maximum number of labels allowed (default: 50) */
142
+ maxLabelCount?: number;
143
+ /** Enable debug logging for transport errors (default: false) */
144
+ debug?: boolean;
145
+ }
146
+ /**
147
+ * Represents a Loki log stream with labels and log values
148
+ */
149
+ export interface LokiStream {
150
+ /** Key-value pairs of log labels */
151
+ stream: {
152
+ /** Log level label (required) */
153
+ level: string;
154
+ /** Additional custom labels */
155
+ [key: string]: string;
156
+ };
157
+ /** Array of log entries with [timestamp, message] pairs */
158
+ values: [
159
+ [
160
+ string,
161
+ string
162
+ ]
163
+ ];
164
+ }
165
+ /**
166
+ * Main Logger class that handles all logging functionality.
167
+ *
168
+ * Provides a structured logging interface with multiple severity levels and
169
+ * support for various transports (console, Loki, NDJSON, etc.).
170
+ *
171
+ * @example
172
+ * // Basic usage
173
+ * const logger = new Logger();
174
+ * logger.info("Application started");
175
+ *
176
+ * @example
177
+ * // With custom configuration
178
+ * const logger = new Logger({
179
+ * level: Levels.DEBUG,
180
+ * transports: [new ConsoleTransport(), new LokiTransport({ url: "http://loki:3100" })]
181
+ * });
182
+ */
183
+ export declare class Logger {
184
+ private level;
185
+ private transports;
159
186
  /**
160
- * Determines if colored output is enabled for log messages.
161
- *
162
- * When set to `true`, log messages will be displayed with color coding to enhance readability and visually distinguish
163
- * different types of log entries. This is particularly useful in environments where color support is available, such as
164
- * modern terminals or command-line interfaces.
165
- *
166
- * When set to `false`, log messages will be output in plain text without any color formatting. This setting might be
167
- * preferred in environments that do not support color, or where color output is not desired.
168
- *
169
- * Example:
170
- * To enable colored log messages:
171
- *
172
- * ```typescript
173
- * Logger.colors = true;
174
- * ```
175
- *
176
- * To disable colored log messages:
177
- *
178
- * ```typescript
179
- * Logger.colors = false;
180
- * ```
181
- *
182
- * @type {boolean}
183
- * @default true
187
+ * Creates a new Logger instance
188
+ * @param config Optional configuration for the logger
189
+ * @param config.level Minimum log level to output (default: INFO)
190
+ * @param config.transports Array of transports to use (default: [ConsoleTransport])
184
191
  */
185
- let colors: boolean;
192
+ constructor(config?: {
193
+ level?: Levels;
194
+ transports?: Transport[];
195
+ });
186
196
  /**
187
- * The format string used to customize the output of log messages.
188
- *
189
- * This format string supports placeholders that are replaced with actual log message data:
190
- * - `{date}`: Replaced with the current timestamp of the log message.
191
- * - `{type}`: Replaced with the log level type (e.g., ERROR, INFO).
192
- * - `{message}`: Replaced with the log message content.
193
- *
194
- * Example usage:
195
- *
196
- * ```js
197
- * // Customizing the log message format
198
- * Logger.format = "[{date}] - {type}: {message}";
199
- *
200
- * // Log a message using the custom format
201
- * Logger.info("This is an informational message.");
202
- * ```
203
- *
204
- * The default format is `"[{date}] {type} {message}"`.
205
- *
206
- * @type {string}
197
+ * Determines if a message should be logged based on its level
198
+ * @private
199
+ * @param level The log level to check
200
+ * @returns True if the message should be logged
207
201
  */
208
- let format: string;
202
+ private shouldLog;
209
203
  /**
210
- * Converts a log message to a string format.
211
- *
212
- * This function ensures that the log message is always returned as a string. If the provided message is an object, it
213
- * will be converted to a JSON string representation using `JSON.stringify`. If the message is `undefined`, the function
214
- * will return `null` to indicate the absence of a message. For all other types of input (e.g., strings, numbers), the
215
- * function will return the message as-is.
216
- *
217
- * This conversion is useful for ensuring that log messages are consistently formatted, especially when handling
218
- * different types of data in logging scenarios.
219
- *
220
- * @param {any} message - The log message to convert. This can be of any type, including strings, numbers, or objects.
221
- *
222
- * @returns {string | null} - The converted log message as a string. Returns `null` if the message is `undefined`. If
223
- * the message is an object, it will be returned as a JSON string.
224
- *
225
- * @example
226
- * // Convert a string message
227
- * const result1 = Logger.parseMessage("An error occurred.");
228
- * // result1 is "An error occurred."
229
- *
230
- * // Convert a number message
231
- * const result2 = Logger.parseMessage(404);
232
- * // result2 is "404"
233
- *
234
- * // Convert an object message
235
- * const result3 = Logger.parseMessage({ error: "Not Found", code: 404 });
236
- * // result3 is '{"error":"Not Found","code":404}'
237
- *
238
- * // Handle an undefined message
239
- * const result4 = Logger.parseMessage(undefined);
240
- * // result4 is null
204
+ * Creates a structured log entry
205
+ * @private
206
+ * @param message The log message
207
+ * @param level The log level
208
+ * @param metadata Optional metadata object
209
+ * @returns Complete LogEntry object
241
210
  */
242
- function parseMessage(message: any): string | null;
211
+ private createLogEntry;
243
212
  /**
244
- * Formats a log message with a timestamp, log level, and optional color styling.
245
- *
246
- * This function creates a formatted string for logging purposes. It includes a timestamp representing when the log
247
- * entry was created, the log level indicating the severity of the message, and the actual log message. Depending on
248
- * whether colored output is enabled, it applies color codes to the timestamp, log level, and message to improve visibility
249
- * and distinction.
250
- *
251
- * **Formatting Process**:
252
- * 1. **Timestamp**: The current date and time is formatted to a readable string in `YYYY-MM-DD HH:MM:SS` format.
253
- * 2. **Log Level**: The log level is converted to its string representation using the `Levels` enum and, if color
254
- * styling is enabled, is styled according to the `LevelColors` mapping.
255
- * 3. **Message**: The actual log message is optionally colored based on the log level.
256
- * 4. **Color Application**: If color output is enabled, ANSI escape codes are applied to the timestamp, log level, and
257
- * message.
258
- *
259
- * @param {string} message - The log message to format. This is the actual content of the log entry and will be included
260
- * in the final formatted string. It should be a string type.
261
- *
262
- * @param {Levels} logLevel - The log level associated with the message. This determines how the log message is categorized
263
- * (e.g., ERROR, INFO) and influences the formatting applied to the log level part of the output.
264
- *
265
- * @returns {string} - The formatted log message as a string. This includes the timestamp, log level, and message,
266
- * with optional color styling based on the `colors` setting.
267
- *
268
- * @example
269
- * // Format an error message with color styling
270
- * const formattedError = Logger.formatMessage("An unexpected error occurred.", Levels.ERROR);
271
- * // Output: [2024-08-11 12:34:56] <colored error level> An unexpected error occurred.
272
- *
273
- * // Format an informational message without color styling
274
- * Logger.colors = false; // Disable color output
275
- * const formattedInfo = Logger.formatMessage("System startup complete.", Levels.INFO);
276
- * // Output: [2024-08-11 12:34:56] INFO System startup complete.
213
+ * Processes a log entry through all configured transports
214
+ * @private
215
+ * @param entry The log entry to process
277
216
  */
278
- function formatMessage(message: string, logLevel: Levels): string;
217
+ private processEntry;
279
218
  /**
280
- * Logs an error message at the `ERROR` log level.
281
- *
282
- * This function formats and logs a message with a severity level of `ERROR`. It processes the provided message,
283
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
284
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
285
- *
286
- * If the current log level is set to a level lower than `ERROR`, the message will not be logged. This function also
287
- * supports various message types, converting non-string messages to a string representation before logging.
288
- *
289
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
290
- * be converted to a string using `JSON.stringify` for structured logging.
291
- *
292
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
293
- * if NDJson logging is enabled.
294
- *
295
- * @example
296
- * // Log an error message
297
- * Logger.error("An unexpected error occurred while processing the request.");
298
- *
299
- * // Log an error message with additional details
300
- * Logger.error({ error: "Network failure", code: 500 });
219
+ * Logs an error message
220
+ * @param message The error message
221
+ * @param metadata Optional metadata object
301
222
  */
302
- function error(message: any): void;
223
+ error(message: string, metadata?: Record<string, any>): void;
303
224
  /**
304
- * Logs a warning message at the `WARN` log level.
305
- *
306
- * This function formats and logs a message with a severity level of `WARN`. It processes the provided message,
307
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
308
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
309
- *
310
- * If the current log level is set to a level lower than `WARN`, the message will not be logged. This function also
311
- * supports various message types, converting non-string messages to a string representation before logging.
312
- *
313
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
314
- * be converted to a string using `JSON.stringify` for structured logging.
315
- *
316
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
317
- * if NDJson logging is enabled.
318
- *
319
- * @example
320
- * // Log a warning message
321
- * Logger.warn("Configuration might be missing some required settings.");
322
- *
323
- * // Log a warning message with additional details
324
- * Logger.warn({ warning: "Disk space is running low", details: { freeSpace: "10MB" } });
225
+ * Logs a warning message
226
+ * @param message The warning message
227
+ * @param metadata Optional metadata object
325
228
  */
326
- function warn(message: any): void;
229
+ warn(message: string, metadata?: Record<string, any>): void;
327
230
  /**
328
- * Logs an informational message at the `INFO` log level.
329
- *
330
- * This function formats and logs a message with a severity level of `INFO`. It processes the provided message,
331
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
332
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
333
- *
334
- * If the current log level is set to a level lower than `INFO`, the message will not be logged. This function also
335
- * supports various message types, converting non-string messages to a string representation before logging.
336
- *
337
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
338
- * be converted to a string using `JSON.stringify` for structured logging.
339
- *
340
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
341
- * if NDJson logging is enabled.
342
- *
343
- * @example
344
- * // Log an informational message
345
- * Logger.info("System startup completed successfully.");
346
- *
347
- * // Log an informational message with additional details
348
- * Logger.info({ event: "UserLogin", user: "john.doe@example.com", status: "success" });
231
+ * Logs an informational message
232
+ * @param message The info message
233
+ * @param metadata Optional metadata object
349
234
  */
350
- function info(message: any): void;
235
+ info(message: string, metadata?: Record<string, any>): void;
351
236
  /**
352
- * Logs HTTP-related message at the `HTTP` log level.
353
- *
354
- * This function formats and logs a message with a severity level of `HTTP`. It processes the provided message,
355
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
356
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
357
- *
358
- * If the current log level is set to a level lower than `HTTP`, the message will not be logged. This function also
359
- * supports various message types, converting non-string messages to a string representation before logging.
360
- *
361
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
362
- * be converted to a string using `JSON.stringify` for structured logging.
363
- *
364
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
365
- * if NDJson logging is enabled.
366
- *
367
- * @example
368
- * // Log HTTP-related message
369
- * Logger.http("Received GET request to /api/resource.");
370
- *
371
- * // Log HTTP-related message with additional details
372
- * Logger.http({ method: "POST", endpoint: "/api/resource", status: 200, responseTime: "150ms" });
237
+ * Logs an HTTP-related message
238
+ * @param message The HTTP message
239
+ * @param metadata Optional metadata object
373
240
  */
374
- function http(message: any): void;
241
+ http(message: string, metadata?: Record<string, any>): void;
375
242
  /**
376
- * Logs a verbose message at the `VERBOSE` log level.
377
- *
378
- * This function formats and logs a message with a severity level of `VERBOSE`. It processes the provided message,
379
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
380
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
381
- *
382
- * If the current log level is set to a level lower than `VERBOSE`, the message will not be logged. This function also
383
- * supports various message types, converting non-string messages to a string representation before logging.
384
- *
385
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
386
- * be converted to a string using `JSON.stringify` for structured logging.
387
- *
388
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
389
- * if NDJson logging is enabled.
390
- *
391
- * @example
392
- * // Log a verbose message
393
- * Logger.verbose("Detailed system status: All services are running optimally.");
394
- *
395
- * // Log a verbose message with additional details
396
- * Logger.verbose({ module: "Database", action: "query", details: "Fetching records from users table" });
243
+ * Logs a verbose message
244
+ * @param message The verbose message
245
+ * @param metadata Optional metadata object
397
246
  */
398
- function verbose(message: any): void;
247
+ verbose(message: string, metadata?: Record<string, any>): void;
399
248
  /**
400
- * Logs a debug message at the `DEBUG` log level.
401
- *
402
- * This function formats and logs a message with a severity level of `DEBUG`. It processes the provided message,
403
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
404
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
405
- *
406
- * If the current log level is set to a level lower than `DEBUG`, the message will not be logged. This function also
407
- * supports various message types, converting non-string messages to a string representation before logging.
408
- *
409
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
410
- * be converted to a string using `JSON.stringify` for structured logging.
411
- *
412
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
413
- * if NDJson logging is enabled.
414
- *
415
- * @example
416
- * // Log a debug message
417
- * Logger.debug("Debugging internal state: variable x = 42, variable y = 'test'");
418
- *
419
- * // Log a debug message with additional details
420
- * Logger.debug({ context: "Initialization", details: "Loading configuration files" });
249
+ * Logs a debug message
250
+ * @param message The debug message
251
+ * @param metadata Optional metadata object
421
252
  */
422
- function debug(message: any): void;
253
+ debug(message: string, metadata?: Record<string, any>): void;
423
254
  /**
424
- * Logs a silly message at the `SILLY` log level.
425
- *
426
- * This function formats and logs a message with a severity level of `SILLY`. It processes the provided message,
427
- * ensuring it is in the correct format, and then outputs it to the console with appropriate styling if colors are enabled.
428
- * Additionally, if NDJson logging is enabled, the message is appended to the NDJson formatted log data.
429
- *
430
- * If the current log level is set to a level lower than `SILLY`, the message will not be logged. This function also
431
- * supports various message types, converting non-string messages to a string representation before logging.
432
- *
433
- * @param {any} message - The message to log. Can be a string or any other type. If the message is not a string, it will
434
- * be converted to a string using `JSON.stringify` for structured logging.
435
- *
436
- * @returns {void} - This function does not return a value. It directly performs logging and modifies internal log data
437
- * if NDJson logging is enabled.
438
- *
439
- * @example
440
- * // Log a silly message
441
- * Logger.silly("This is a silly log message, meant for fun and not serious debugging.");
442
- *
443
- * // Log a silly message with additional details
444
- * Logger.silly({ reason: "Unexpected behavior", details: "Just a whimsical message" });
255
+ * Logs a silly message (lowest level)
256
+ * @param message The silly message
257
+ * @param metadata Optional metadata object
445
258
  */
446
- function silly(message: any): void;
259
+ silly(message: string, metadata?: Record<string, any>): void;
447
260
  /**
448
- * Appends a log message to the NDJson (Newline Delimited JSON) formatted log.
449
- *
450
- * NDJson is a format where each log entry is a separate JSON object, and each object is separated by a newline character.
451
- * This format is particularly useful for structured logging, log aggregation, and processing in systems that require
452
- * newline-delimited JSON entries. This function adds a new log entry with the current timestamp, the specified log level,
453
- * and the provided message to the NDJson formatted log data.
454
- *
455
- * If NDJson logging is not enabled, or if no log entries have been recorded yet, this function will still format the log
456
- * entry correctly and append it to the internal storage.
457
- *
458
- * @param {string} message - The log message to append. This should be a string that represents the content of the log entry.
459
- * @param {number} logLevel - The log level associated with the message. This should correspond to one of the predefined
460
- * log levels, which indicate the severity or type of the log entry.
461
- *
462
- * @returns {void} - This function does not return a value. It modifies the internal NDJson data directly.
463
- *
464
- * @example
465
- * // Append an error log message to the NDJson formatted log
466
- * Logger.putNDJson("An error occurred while processing the request.", Levels.ERROR);
467
- *
468
- * // Append an informational log message
469
- * Logger.putNDJson("User login successful.", Levels.INFO);
261
+ * Adds a new transport to the logger
262
+ * @param transport The transport to add
470
263
  */
471
- function putNDJson(message: string, logLevel: number): void;
264
+ addTransport(transport: Transport): void;
472
265
  /**
473
- * Retrieves the log data in NDJson (Newline Delimited JSON) format.
474
- *
475
- * This function returns a string containing all log entries that have been stored in NDJson format. NDJson format is
476
- * useful for structured logging and is commonly used for log aggregation and processing systems. Each log entry is
477
- * represented as a separate JSON object, making it easy to parse and analyze logs.
478
- *
479
- * If NDJson logging is not enabled or no logs have been recorded, this function will return an empty string.
480
- *
481
- * Example:
482
- * To get the NDJson formatted logs:
483
- *
484
- * ```typescript
485
- * const ndjsonLogs = Logger.getNDJson();
486
- * console.log(ndjsonLogs);
487
- * ```
488
- *
489
- * @returns {string} - A string containing the NDJson formatted log data. If no logs are available, returns an empty string.
266
+ * Removes a transport from the logger
267
+ * @param transport The transport to remove
490
268
  */
491
- function getNDJson(): string;
269
+ removeTransport(transport: Transport): void;
492
270
  /**
493
- * Resets the NDJson log data.
494
- *
495
- * This function clears the internal storage of NDJson formatted logs by setting `NDJsonData` to an empty string.
496
- * It effectively erases all previously logged NDJson entries, which might be useful for starting a new logging session
497
- * or clearing out old logs before logging new data.
498
- *
499
- * Example usage:
500
- * ```typescript
501
- * Logger.resetNDJson(); // Clears the NDJson log data
502
- * ```
503
- *
504
- * Note: This action is irreversible, and any log data previously accumulated in NDJson format will be lost.
271
+ * Sets the minimum log level
272
+ * @param level The new minimum log level
505
273
  */
506
- function resetNDJson(): void;
274
+ setLevel(level: Levels): void;
275
+ }
276
+ /**
277
+ * Transport that outputs logs to the console with configurable formatting
278
+ */
279
+ export declare class ConsoleTransport implements Transport {
280
+ private format;
281
+ private colors;
282
+ /**
283
+ * Create a ConsoleTransport instance
284
+ * @param format Format string using {date}, {type}, {message} placeholders
285
+ * @param colors Enable colored output
286
+ */
287
+ constructor(format?: string, colors?: boolean);
288
+ /**
289
+ * Output a log entry to the console
290
+ * @param entry The log entry to output
291
+ */
292
+ log(entry: LogEntry): void;
293
+ }
294
+ /**
295
+ * Transport that collects logs in NDJSON (Newline Delimited JSON) format
296
+ */
297
+ export declare class NDJsonTransport implements Transport {
298
+ private data;
299
+ /**
300
+ * Append a log entry to the NDJSON buffer
301
+ * @param entry The log entry to append
302
+ */
303
+ log(entry: LogEntry): void;
304
+ /**
305
+ * Get the accumulated NDJSON data
306
+ * @returns The NDJSON formatted log data
307
+ */
308
+ getData(): string;
309
+ /**
310
+ * Clear the accumulated log data
311
+ */
312
+ reset(): void;
313
+ }
314
+ /**
315
+ * Transport that sends logs to a Grafana Loki server
316
+ */
317
+ export declare class LokiTransport implements Transport {
318
+ private config;
319
+ private batch;
320
+ private batchSize;
321
+ private batchTimeout;
322
+ private timeoutHandle?;
323
+ private maxLabelCount;
324
+ private debug;
325
+ /**
326
+ * Create a LokiTransport instance
327
+ * @param config Configuration options for Loki
328
+ * @throws {Error} If URL is not provided
329
+ */
330
+ constructor(config: LokiConfig);
331
+ /**
332
+ * Add a log entry to the batch (may trigger send if batch size is reached)
333
+ * @param entry The log entry to send
334
+ */
335
+ log(entry: LogEntry): void;
336
+ /**
337
+ * Send the current batch of logs to Loki
338
+ * @private
339
+ */
340
+ private sendBatch;
507
341
  }
508
-
509
- export {
510
- Logger as default,
511
- };
512
342
 
513
343
  export {};