@rabbit-company/logger 4.0.0 → 5.1.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,113 +1,279 @@
1
- # Logger-JS
1
+ # @rabbit-company/logger 🐇📝
2
2
 
3
- `Logger-JS` is a lightweight logging utility for JavaScript (ES6) that provides various logging levels and supports NDJson formatting for structured logging.
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
- ## Table of Contents
7
+ A versatile, multi-transport logging library for Node.js and browser environments with support for:
6
8
 
7
- 1. [Installation](#installation)
8
- 2. [Importing the Library](#importing-the-library)
9
- 3. [Configuration](#configuration)
10
- 4. [Logging Messages](#logging-messages)
11
- 5. [NDJson Logging](#ndjson-logging)
12
- 6. [Customization](#customization)
9
+ - Console output (with colors and custom formatting)
10
+ - NDJSON (Newline Delimited JSON)
11
+ - Grafana Loki (with batching and label management)
13
12
 
14
- ## Installation
13
+ ## Features ✨
15
14
 
16
- To install `Logger-JS`, use npm to add it to your project:
15
+ - **Multiple log levels**: ERROR, WARN, AUDIT, INFO, HTTP, DEBUG, VERBOSE, 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 📦
17
23
 
18
24
  ```bash
19
- npm i --save @rabbit-company/logger
20
- ```
25
+ # npm
26
+ npm install @rabbit-company/logger
21
27
 
22
- ## Importing the Library
28
+ # yarn
29
+ yarn add @rabbit-company/logger
30
+
31
+ # pnpm
32
+ pnpm add @rabbit-company/logger
33
+ ```
23
34
 
24
- After installation, you can import the `Logger` into your JavaScript file:
35
+ ## Basic Usage 🚀
25
36
 
26
37
  ```js
27
- import Logger from "@rabbit-company/logger";
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
+ });
28
49
  ```
29
50
 
30
- ## Configuration
51
+ ## Console Formatting 🖥️
31
52
 
32
- Configure the logger to suit your needs. You can set the log level to control which types of messages are logged:
53
+ The console transport supports extensive datetime formatting:
33
54
 
34
- ```js
35
- // Set the log level to SILLY to enable all levels of logging
36
- Logger.level = Logger.Levels.SILLY;
55
+ ### Available Placeholders
37
56
 
38
- // Enable or disable colored output
39
- Logger.colors = true; // Set to false to disable colors
57
+ #### UTC Formats:
40
58
 
41
- // Enable or disable NDJson logging
42
- Logger.NDJson = false; // Set to true to enable NDJson logging
59
+ - `{iso}`: Full ISO-8601 (2023-11-15T14:30:45.123Z)
60
+ - `{datetime}`: Simplified (2023-11-15 14:30:45)
61
+ - `{date}`: Date only (2023-11-15)
62
+ - `{time}`: Time only (14:30:45)
63
+ - `{utc}`: UTC string (Wed, 15 Nov 2023 14:30:45 GMT)
64
+ - `{ms}`: Milliseconds since epoch
65
+
66
+ #### Local Time Formats:
67
+
68
+ - `{datetime-local}`: Local datetime (2023-11-15 14:30:45)
69
+ - `{date-local}`: Local date only (2023-11-15)
70
+ - `{time-local}`: Local time only (14:30:45)
71
+ - `{full-local}`: Complete local string with timezone
72
+
73
+ #### Log Content:
74
+
75
+ - `{type}`: Log level (INFO, ERROR, etc.)
76
+ - `{message}`: The log message
77
+
78
+ ```js
79
+ import { ConsoleTransport } from "@rabbit-company/logger";
80
+
81
+ // Custom format examples
82
+ new ConsoleTransport("[{datetime-local}] {type} {message}");
83
+ new ConsoleTransport("{time} | {type} | {message}", false);
84
+ new ConsoleTransport("EPOCH:{ms} {message}");
43
85
  ```
44
86
 
45
- ## Logging Messages
87
+ ## Transports 🚚
46
88
 
47
- Use the provided methods to log messages at different levels of severity:
89
+ ### Console Transport (Default)
48
90
 
49
91
  ```js
50
- // Log an error message
51
- Logger.error("This is an error message.");
92
+ import { ConsoleTransport } from "@rabbit-company/logger";
93
+
94
+ const logger = new Logger({
95
+ transports: [
96
+ new ConsoleTransport(
97
+ "[{time-local}] {type} {message}", // Custom format
98
+ true // Enable colors
99
+ ),
100
+ ],
101
+ });
102
+ ```
52
103
 
53
- // Log a warning message
54
- Logger.warn("This is a warning message.");
104
+ ### NDJSON Transport
55
105
 
56
- // Log an informational message
57
- Logger.info("This is an informational message.");
106
+ ```js
107
+ import { NDJsonTransport } from "@rabbit-company/logger";
58
108
 
59
- // Log an HTTP-related message
60
- Logger.http("This is an HTTP-related message.");
109
+ const ndjsonTransport = new NDJsonTransport();
110
+ const logger = new Logger({
111
+ transports: [ndjsonTransport],
112
+ });
61
113
 
62
- // Log a verbose message
63
- Logger.verbose("This is a verbose message.");
114
+ // Get accumulated logs
115
+ console.log(ndjsonTransport.getData());
116
+ ```
64
117
 
65
- // Log a debug message
66
- Logger.debug("This is a debug message.");
118
+ ### Loki Transport
67
119
 
68
- // Log a silly message
69
- Logger.silly("This is a silly message.");
120
+ ```js
121
+ import { LokiTransport } from "@rabbit-company/logger";
122
+
123
+ const logger = new Logger({
124
+ transports: [
125
+ new LokiTransport({
126
+ url: "http://localhost:3100",
127
+ labels: { app: "my-app", env: "production" },
128
+ basicAuth: { username: "user", password: "pass" },
129
+ maxLabelCount: 30,
130
+ }),
131
+ ],
132
+ });
70
133
  ```
71
134
 
72
- ## NDJson Logging
135
+ ## API Reference 📚
73
136
 
74
- When NDJson logging is enabled, log messages are formatted as newline-delimited JSON. You can retrieve the NDJson formatted log using:
137
+ ### Log Levels
75
138
 
76
139
  ```js
77
- // Enable NDJson logging
78
- Logger.NDJson = true;
140
+ enum Levels {
141
+ ERROR, // Critical errors
142
+ WARN, // Warnings
143
+ AUDIT, // Security audits
144
+ INFO, // Informational
145
+ HTTP, // HTTP traffic
146
+ DEBUG, // Debugging
147
+ VERBOSE, // Detailed tracing
148
+ SILLY // Very low-level
149
+ }
150
+ ```
79
151
 
80
- // Retrieve NDJson log data
81
- const ndjsonLog = Logger.getNDJson();
82
- console.log(ndjsonLog);
152
+ ### Logging Methods
83
153
 
84
- // Clear NDJson log data
85
- Logger.resetNDJson();
154
+ ```js
155
+ logger.error(message: string, metadata?: object): void
156
+ logger.warn(message: string, metadata?: object): void
157
+ logger.audit(message: string, metadata?: object): void
158
+ logger.info(message: string, metadata?: object): void
159
+ logger.http(message: string, metadata?: object): void
160
+ logger.verbose(message: string, metadata?: object): void
161
+ logger.debug(message: string, metadata?: object): void
162
+ logger.silly(message: string, metadata?: object): void
86
163
  ```
87
164
 
88
- ## Customization
165
+ ### Types
166
+
167
+ ```ts
168
+ /**
169
+ * Represents a single log entry with message, severity level, timestamp, and optional metadata
170
+ */
171
+ export interface LogEntry {
172
+ /** The log message content */
173
+ message: string;
174
+ /** Severity level of the log entry */
175
+ level: Levels;
176
+ /** Timestamp in milliseconds since epoch */
177
+ timestamp: number;
178
+ /** Optional structured metadata associated with the log */
179
+ metadata?: Record<string, any>;
180
+ }
181
+
182
+ /**
183
+ * Interface for log transport implementations
184
+ */
185
+ export interface Transport {
186
+ /**
187
+ * Processes and outputs a log entry
188
+ * @param entry The log entry to process
189
+ */
190
+ log: (entry: LogEntry) => void;
191
+ }
192
+
193
+ /**
194
+ * Configuration options for the Logger instance
195
+ */
196
+ export interface LoggerConfig {
197
+ /** Minimum log level to output (default: INFO) */
198
+ level?: Levels;
199
+ /** Enable colored output (default: true) */
200
+ colors?: boolean;
201
+ /** Format string using {date}, {type}, {message} placeholders (default: "[{date}] {type} {message}") */
202
+ format?: string;
203
+ /** Array of transports to use (default: [ConsoleTransport]) */
204
+ transports?: Transport[];
205
+ }
206
+
207
+ /**
208
+ * Configuration for Loki transport
209
+ */
210
+ export interface LokiConfig {
211
+ /** Loki server URL (e.g., "http://localhost:3100") */
212
+ url: string;
213
+ /** Base labels to attach to all logs */
214
+ labels?: Record<string, string>;
215
+ /** Basic authentication credentials */
216
+ basicAuth?: {
217
+ username: string;
218
+ password: string;
219
+ };
220
+ /** Number of logs to batch before sending (default: 10) */
221
+ batchSize?: number;
222
+ /** Maximum time in ms to wait before sending a batch (default: 5000) */
223
+ batchTimeout?: number;
224
+ /** Tenant ID for multi-tenant Loki setups */
225
+ tenantID?: string;
226
+ /** Maximum number of labels allowed (default: 50) */
227
+ maxLabelCount?: number;
228
+ /** Enable debug logging for transport errors (default: false) */
229
+ debug?: boolean;
230
+ }
231
+
232
+ /**
233
+ * Represents a Loki log stream with labels and log values
234
+ */
235
+ export interface LokiStream {
236
+ /** Key-value pairs of log labels */
237
+ stream: {
238
+ /** Log level label (required) */
239
+ level: string;
240
+ /** Additional custom labels */
241
+ [key: string]: string;
242
+ };
243
+ /** Array of log entries with [timestamp, message] pairs */
244
+ values: [[string, string]];
245
+ }
246
+ ```
89
247
 
90
- ### 1. Customizing Log Colors
248
+ ## Advanced Usage 🛠️
91
249
 
92
- You can customize the colors associated with different logging levels by modifying the `LevelColors` mapping:
250
+ ### Custom Formatting
93
251
 
94
252
  ```js
95
- // Change colors for different log levels
96
- Logger.LevelColors[Logger.Levels.ERROR] = Logger.Colors.BRIGHT_RED;
97
- Logger.LevelColors[Logger.Levels.INFO] = Logger.Colors.GREEN;
253
+ new ConsoleTransport(
254
+ "{type} - {date} - {message}", // Custom format
255
+ false // Disable colors
256
+ );
98
257
  ```
99
258
 
100
- ### 2. Customizing Log Message Format
259
+ ### Managing Transports
101
260
 
102
- You can also customize the format of the log messages by setting the `Logger.format` string. This format string can include the following placeholders:
261
+ ```js
262
+ const lokiTransport = new LokiTransport({
263
+ /* config */
264
+ });
265
+ const logger = new Logger();
103
266
 
104
- - `{date}`: Inserts the current timestamp.
105
- - `{type}`: Inserts the log level type (e.g., ERROR, INFO).
106
- - `{message}`: Inserts the actual log message.
267
+ // Add transport dynamically
268
+ logger.addTransport(lokiTransport);
107
269
 
108
- Example of customizing the log format:
270
+ // Remove transport
271
+ logger.removeTransport(lokiTransport);
109
272
 
110
- ```js
111
- // Set a custom log message format
112
- Logger.format = "[{date}] - {type}: {message}";
273
+ // Change log level
274
+ logger.setLevel(Levels.VERBOSE);
113
275
  ```
276
+
277
+ ## License 📄
278
+
279
+ This project is licensed under the MIT License - see the [LICENSE](https://github.com/Rabbit-Company/Logger-JS/blob/main/LICENSE) file for details.