@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.
package/README.md CHANGED
@@ -1,113 +1,241 @@
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, 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
17
21
 
18
- ```bash
19
- npm i --save @rabbit-company/logger
20
- ```
22
+ ## Installation 📦
21
23
 
22
- ## Importing the Library
24
+ ```bash
25
+ # npm
26
+ npm install @rabbit-company/logger
23
27
 
24
- After installation, you can import the `Logger` into your JavaScript file:
28
+ # yarn
29
+ yarn add @rabbit-company/logger
25
30
 
26
- ```js
27
- import Logger from "@rabbit-company/logger";
31
+ # pnpm
32
+ pnpm add @rabbit-company/logger
28
33
  ```
29
34
 
30
- ## Configuration
31
-
32
- Configure the logger to suit your needs. You can set the log level to control which types of messages are logged:
35
+ ## Basic Usage 🚀
33
36
 
34
37
  ```js
35
- // Set the log level to SILLY to enable all levels of logging
36
- Logger.level = Logger.Levels.SILLY;
38
+ import { Logger, Levels } from "@rabbit-company/logger";
37
39
 
38
- // Enable or disable colored output
39
- Logger.colors = true; // Set to false to disable colors
40
+ // Create logger with default console transport
41
+ const logger = new Logger({ level: Levels.DEBUG });
40
42
 
41
- // Enable or disable NDJson logging
42
- Logger.NDJson = false; // Set to true to enable NDJson logging
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
+ });
43
49
  ```
44
50
 
45
- ## Logging Messages
51
+ ## Transports 🚚
46
52
 
47
- Use the provided methods to log messages at different levels of severity:
53
+ ### Console Transport (Default)
48
54
 
49
55
  ```js
50
- // Log an error message
51
- Logger.error("This is an error message.");
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
+ });
66
+ ```
52
67
 
53
- // Log a warning message
54
- Logger.warn("This is a warning message.");
68
+ ### NDJSON Transport
55
69
 
56
- // Log an informational message
57
- Logger.info("This is an informational message.");
70
+ ```js
71
+ import { NDJsonTransport } from "@rabbit-company/logger";
58
72
 
59
- // Log an HTTP-related message
60
- Logger.http("This is an HTTP-related message.");
73
+ const ndjsonTransport = new NDJsonTransport();
74
+ const logger = new Logger({
75
+ transports: [ndjsonTransport],
76
+ });
61
77
 
62
- // Log a verbose message
63
- Logger.verbose("This is a verbose message.");
78
+ // Get accumulated logs
79
+ console.log(ndjsonTransport.getData());
80
+ ```
64
81
 
65
- // Log a debug message
66
- Logger.debug("This is a debug message.");
82
+ ### Loki Transport
67
83
 
68
- // Log a silly message
69
- Logger.silly("This is a silly message.");
84
+ ```js
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
+ });
70
97
  ```
71
98
 
72
- ## NDJson Logging
99
+ ## API Reference 📚
73
100
 
74
- When NDJson logging is enabled, log messages are formatted as newline-delimited JSON. You can retrieve the NDJson formatted log using:
101
+ ### Log Levels
75
102
 
76
103
  ```js
77
- // Enable NDJson logging
78
- Logger.NDJson = true;
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
+ ```
79
114
 
80
- // Retrieve NDJson log data
81
- const ndjsonLog = Logger.getNDJson();
82
- console.log(ndjsonLog);
115
+ ### Logging Methods
83
116
 
84
- // Clear NDJson log data
85
- Logger.resetNDJson();
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
86
125
  ```
87
126
 
88
- ## Customization
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
+ ```
89
209
 
90
- ### 1. Customizing Log Colors
210
+ ## Advanced Usage 🛠️
91
211
 
92
- You can customize the colors associated with different logging levels by modifying the `LevelColors` mapping:
212
+ ### Custom Formatting
93
213
 
94
214
  ```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;
215
+ new ConsoleTransport(
216
+ "{type} - {date} - {message}", // Custom format
217
+ false // Disable colors
218
+ );
98
219
  ```
99
220
 
100
- ### 2. Customizing Log Message Format
221
+ ### Managing Transports
101
222
 
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:
223
+ ```js
224
+ const lokiTransport = new LokiTransport({
225
+ /* config */
226
+ });
227
+ const logger = new Logger();
103
228
 
104
- - `{date}`: Inserts the current timestamp.
105
- - `{type}`: Inserts the log level type (e.g., ERROR, INFO).
106
- - `{message}`: Inserts the actual log message.
229
+ // Add transport dynamically
230
+ logger.addTransport(lokiTransport);
107
231
 
108
- Example of customizing the log format:
232
+ // Remove transport
233
+ logger.removeTransport(lokiTransport);
109
234
 
110
- ```js
111
- // Set a custom log message format
112
- Logger.format = "[{date}] - {type}: {message}";
235
+ // Change log level
236
+ logger.setLevel(Levels.VERBOSE);
113
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.