@rabbit-company/logger 3.1.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.
package/README.md CHANGED
@@ -1,31 +1,241 @@
1
- # Logger-JS
1
+ # @rabbit-company/logger 🐇📝
2
2
 
3
- Simple Logger implementation in JavaScript (ES6).
3
+ [![NPM Version](https://img.shields.io/npm/v/@rabbit-company/logger)](https://www.npmjs.com/package/@rabbit-company/logger)
4
+ [![JSR Version](https://jsr.io/badges/@rabbit-company/logger)](https://jsr.io/@rabbit-company/logger)
5
+ [![License](https://img.shields.io/npm/l/@rabbit-company/logger)](LICENSE)
4
6
 
5
- ## Usage
7
+ A versatile, multi-transport logging library for Node.js and browser environments with support for:
8
+
9
+ - Console output (with colors and custom formatting)
10
+ - NDJSON (Newline Delimited JSON)
11
+ - Grafana Loki (with batching and label management)
12
+
13
+ ## Features ✨
14
+
15
+ - **Multiple log levels**: ERROR, WARN, INFO, HTTP, VERBOSE, DEBUG, SILLY
16
+ - **Structured logging**: Attach metadata objects to log entries
17
+ - **Transport system**: Console, NDJSON, and Loki transports included
18
+ - **Loki optimized**: Automatic label management and batching
19
+ - **TypeScript ready**: Full type definitions included
20
+ - **Cross-platform**: Works in Node.js, Deno, Bun and browsers
21
+
22
+ ## Installation 📦
6
23
 
7
- ### 1. Download library
8
24
  ```bash
9
- npm i --save @rabbit-company/logger
25
+ # npm
26
+ npm install @rabbit-company/logger
27
+
28
+ # yarn
29
+ yarn add @rabbit-company/logger
30
+
31
+ # pnpm
32
+ pnpm add @rabbit-company/logger
33
+ ```
34
+
35
+ ## Basic Usage 🚀
36
+
37
+ ```js
38
+ import { Logger, Levels } from "@rabbit-company/logger";
39
+
40
+ // Create logger with default console transport
41
+ const logger = new Logger({ level: Levels.DEBUG });
42
+
43
+ // Log messages with metadata
44
+ logger.info("Application started", { version: "1.0.0" });
45
+ logger.error("Database connection failed", {
46
+ error: "Connection timeout",
47
+ attempt: 3,
48
+ });
49
+ ```
50
+
51
+ ## Transports 🚚
52
+
53
+ ### Console Transport (Default)
54
+
55
+ ```js
56
+ import { ConsoleTransport } from "@rabbit-company/logger";
57
+
58
+ const logger = new Logger({
59
+ transports: [
60
+ new ConsoleTransport(
61
+ "[{date}] {type} {message}", // Custom format
62
+ true // Enable colors
63
+ ),
64
+ ],
65
+ });
10
66
  ```
11
67
 
12
- ### 2. Import library
68
+ ### NDJSON Transport
69
+
13
70
  ```js
14
- import Logger from "@rabbit-company/logger";
71
+ import { NDJsonTransport } from "@rabbit-company/logger";
72
+
73
+ const ndjsonTransport = new NDJsonTransport();
74
+ const logger = new Logger({
75
+ transports: [ndjsonTransport],
76
+ });
77
+
78
+ // Get accumulated logs
79
+ console.log(ndjsonTransport.getData());
15
80
  ```
16
81
 
17
- ### 3. Change Settings
82
+ ### Loki Transport
83
+
18
84
  ```js
19
- // Enable all log levels
20
- Logger.level = 6;
85
+ import { LokiTransport } from "@rabbit-company/logger";
86
+
87
+ const logger = new Logger({
88
+ transports: [
89
+ new LokiTransport({
90
+ url: "http://localhost:3100",
91
+ labels: { app: "my-app", env: "production" },
92
+ basicAuth: { username: "user", password: "pass" },
93
+ maxLabelCount: 30,
94
+ }),
95
+ ],
96
+ });
21
97
  ```
22
98
 
23
- ### 4. Start logging
99
+ ## API Reference 📚
100
+
101
+ ### Log Levels
102
+
24
103
  ```js
25
- Logger.error(message);
26
- Logger.warn(message);
27
- Logger.info(message);
28
- Logger.http(message);
29
- Logger.verbose(message);
30
- Logger.debug(message);
31
- ```
104
+ enum Levels {
105
+ ERROR, // Critical errors
106
+ WARN, // Warnings
107
+ INFO, // Informational messages
108
+ HTTP, // HTTP-related logs
109
+ VERBOSE, // Verbose debugging
110
+ DEBUG, // Debug messages
111
+ SILLY // Very low-level logs
112
+ }
113
+ ```
114
+
115
+ ### Logging Methods
116
+
117
+ ```js
118
+ logger.error(message: string, metadata?: object): void
119
+ logger.warn(message: string, metadata?: object): void
120
+ logger.info(message: string, metadata?: object): void
121
+ logger.http(message: string, metadata?: object): void
122
+ logger.verbose(message: string, metadata?: object): void
123
+ logger.debug(message: string, metadata?: object): void
124
+ logger.silly(message: string, metadata?: object): void
125
+ ```
126
+
127
+ ### Types
128
+
129
+ ```ts
130
+ /**
131
+ * Represents a single log entry with message, severity level, timestamp, and optional metadata
132
+ */
133
+ export interface LogEntry {
134
+ /** The log message content */
135
+ message: string;
136
+ /** Severity level of the log entry */
137
+ level: Levels;
138
+ /** Timestamp in milliseconds since epoch */
139
+ timestamp: number;
140
+ /** Optional structured metadata associated with the log */
141
+ metadata?: Record<string, any>;
142
+ }
143
+
144
+ /**
145
+ * Interface for log transport implementations
146
+ */
147
+ export interface Transport {
148
+ /**
149
+ * Processes and outputs a log entry
150
+ * @param entry The log entry to process
151
+ */
152
+ log: (entry: LogEntry) => void;
153
+ }
154
+
155
+ /**
156
+ * Configuration options for the Logger instance
157
+ */
158
+ export interface LoggerConfig {
159
+ /** Minimum log level to output (default: INFO) */
160
+ level?: Levels;
161
+ /** Enable colored output (default: true) */
162
+ colors?: boolean;
163
+ /** Format string using {date}, {type}, {message} placeholders (default: "[{date}] {type} {message}") */
164
+ format?: string;
165
+ /** Array of transports to use (default: [ConsoleTransport]) */
166
+ transports?: Transport[];
167
+ }
168
+
169
+ /**
170
+ * Configuration for Loki transport
171
+ */
172
+ export interface LokiConfig {
173
+ /** Loki server URL (e.g., "http://localhost:3100") */
174
+ url: string;
175
+ /** Base labels to attach to all logs */
176
+ labels?: Record<string, string>;
177
+ /** Basic authentication credentials */
178
+ basicAuth?: {
179
+ username: string;
180
+ password: string;
181
+ };
182
+ /** Number of logs to batch before sending (default: 10) */
183
+ batchSize?: number;
184
+ /** Maximum time in ms to wait before sending a batch (default: 5000) */
185
+ batchTimeout?: number;
186
+ /** Tenant ID for multi-tenant Loki setups */
187
+ tenantID?: string;
188
+ /** Maximum number of labels allowed (default: 50) */
189
+ maxLabelCount?: number;
190
+ /** Enable debug logging for transport errors (default: false) */
191
+ debug?: boolean;
192
+ }
193
+
194
+ /**
195
+ * Represents a Loki log stream with labels and log values
196
+ */
197
+ export interface LokiStream {
198
+ /** Key-value pairs of log labels */
199
+ stream: {
200
+ /** Log level label (required) */
201
+ level: string;
202
+ /** Additional custom labels */
203
+ [key: string]: string;
204
+ };
205
+ /** Array of log entries with [timestamp, message] pairs */
206
+ values: [[string, string]];
207
+ }
208
+ ```
209
+
210
+ ## Advanced Usage 🛠️
211
+
212
+ ### Custom Formatting
213
+
214
+ ```js
215
+ new ConsoleTransport(
216
+ "{type} - {date} - {message}", // Custom format
217
+ false // Disable colors
218
+ );
219
+ ```
220
+
221
+ ### Managing Transports
222
+
223
+ ```js
224
+ const lokiTransport = new LokiTransport({
225
+ /* config */
226
+ });
227
+ const logger = new Logger();
228
+
229
+ // Add transport dynamically
230
+ logger.addTransport(lokiTransport);
231
+
232
+ // Remove transport
233
+ logger.removeTransport(lokiTransport);
234
+
235
+ // Change log level
236
+ logger.setLevel(Levels.VERBOSE);
237
+ ```
238
+
239
+ ## License 📄
240
+
241
+ This project is licensed under the MIT License - see the [LICENSE](https://github.com/Rabbit-Company/Logger-JS/blob/main/LICENSE) file for details.
@@ -1,94 +1,343 @@
1
1
  /**
2
- * Represents a logger utility for logging messages with different log levels.
3
- */
4
- export default class Logger {
5
- private static NDJsonData;
6
- /**
7
- * Indicates whether NDJson is enabled.
8
- * @type {boolean}
9
- */
10
- static NDJson: boolean;
11
- /**
12
- * The log level of the logger.
13
- * @type {number}
14
- */
15
- static level: number;
16
- /**
17
- * Indicates whether colors are enabled for log messages.
18
- * @type {boolean}
19
- */
20
- static colors: boolean;
21
- /**
22
- * Defines log levels and their associated numeric values.
23
- * @type {Record<string, number>}
24
- */
25
- static readonly levels: Record<string, number>;
26
- private static readonly levelsRev;
27
- /**
28
- * Parses the log message to ensure it is a string.
29
- * @param {*} message - The log message.
30
- * @returns {string | null} - The parsed log message or null if the message is undefined.
31
- */
32
- static parseMessage(message: any): string | null;
33
- /**
34
- * Formats the log message with timestamp and log level.
35
- * @param {string} message - The log message.
36
- * @param {number} logLevel - The log level.
37
- * @returns {string} - The formatted log message.
38
- */
39
- static formatMessage(message: string, logLevel: number): string;
40
- /**
41
- * Processes and logs a message with the specified log level.
42
- * @param {*} message - The log message.
43
- * @param {number} logLevel - The log level.
44
- */
45
- private static processMessage;
46
- /**
47
- * Logs an error message.
48
- * @param {*} message - The error message.
49
- */
50
- static error(message: any): void;
51
- /**
52
- * Logs a warning message.
53
- * @param {*} message - The warning message.
54
- */
55
- static warn(message: any): void;
56
- /**
57
- * Logs an informational message.
58
- * @param {*} message - The informational message.
59
- */
60
- static info(message: any): void;
61
- /**
62
- * Logs an HTTP-related message.
63
- * @param {*} message - The HTTP-related message.
64
- */
65
- static http(message: any): void;
66
- /**
67
- * Logs a verbose message.
68
- * @param {*} message - The verbose message.
69
- */
70
- static verbose(message: any): void;
71
- /**
72
- * Logs a debug message.
73
- * @param {*} message - The debug message.
74
- */
75
- static debug(message: any): void;
76
- /**
77
- * Logs a silly message.
78
- * @param {*} message - The silly message.
79
- */
80
- static silly(message: any): void;
81
- /**
82
- * Appends a message to NDJson format.
83
- * @param {string} message - The message to append.
84
- * @param {number} logLevel - The log level associated with the message.
85
- */
86
- static putNDJson(message: string, logLevel: number): void;
87
- /**
88
- * Gets the NDJson log.
89
- * @returns {string} - The NDJson log.
90
- */
91
- static getNDJson(): string;
2
+ * Enum representing various text colors for terminal output using ANSI escape codes.
3
+ * @readonly
4
+ */
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,
60
+ /**
61
+ * Informational level. Provides general information about the application's state.
62
+ * Use for normal operational messages that highlight progress.
63
+ */
64
+ INFO = 2,
65
+ /**
66
+ * HTTP-related level. Logs HTTP requests and responses.
67
+ * Use for tracking HTTP API calls and their status.
68
+ */
69
+ HTTP = 3,
70
+ /**
71
+ * Verbose level. Provides detailed information for in-depth analysis.
72
+ * Use for detailed operational logs that are typically only needed during debugging.
73
+ */
74
+ VERBOSE = 4,
75
+ /**
76
+ * Debug level. Provides detailed context for debugging purposes.
77
+ * Use for extended debugging information during development.
78
+ */
79
+ DEBUG = 5,
80
+ /**
81
+ * Silly level. Logs very low-level messages.
82
+ * Use for extremely verbose logging messages.
83
+ */
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;
186
+ /**
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])
191
+ */
192
+ constructor(config?: {
193
+ level?: Levels;
194
+ transports?: Transport[];
195
+ });
196
+ /**
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
201
+ */
202
+ private shouldLog;
203
+ /**
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
210
+ */
211
+ private createLogEntry;
212
+ /**
213
+ * Processes a log entry through all configured transports
214
+ * @private
215
+ * @param entry The log entry to process
216
+ */
217
+ private processEntry;
218
+ /**
219
+ * Logs an error message
220
+ * @param message The error message
221
+ * @param metadata Optional metadata object
222
+ */
223
+ error(message: string, metadata?: Record<string, any>): void;
224
+ /**
225
+ * Logs a warning message
226
+ * @param message The warning message
227
+ * @param metadata Optional metadata object
228
+ */
229
+ warn(message: string, metadata?: Record<string, any>): void;
230
+ /**
231
+ * Logs an informational message
232
+ * @param message The info message
233
+ * @param metadata Optional metadata object
234
+ */
235
+ info(message: string, metadata?: Record<string, any>): void;
236
+ /**
237
+ * Logs an HTTP-related message
238
+ * @param message The HTTP message
239
+ * @param metadata Optional metadata object
240
+ */
241
+ http(message: string, metadata?: Record<string, any>): void;
242
+ /**
243
+ * Logs a verbose message
244
+ * @param message The verbose message
245
+ * @param metadata Optional metadata object
246
+ */
247
+ verbose(message: string, metadata?: Record<string, any>): void;
248
+ /**
249
+ * Logs a debug message
250
+ * @param message The debug message
251
+ * @param metadata Optional metadata object
252
+ */
253
+ debug(message: string, metadata?: Record<string, any>): void;
254
+ /**
255
+ * Logs a silly message (lowest level)
256
+ * @param message The silly message
257
+ * @param metadata Optional metadata object
258
+ */
259
+ silly(message: string, metadata?: Record<string, any>): void;
260
+ /**
261
+ * Adds a new transport to the logger
262
+ * @param transport The transport to add
263
+ */
264
+ addTransport(transport: Transport): void;
265
+ /**
266
+ * Removes a transport from the logger
267
+ * @param transport The transport to remove
268
+ */
269
+ removeTransport(transport: Transport): void;
270
+ /**
271
+ * Sets the minimum log level
272
+ * @param level The new minimum log level
273
+ */
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;
92
341
  }
93
342
 
94
343
  export {};