voltlog-io 1.0.1 → 1.0.2

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Rohit Tiwari
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Rohit Tiwari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,65 +1,343 @@
1
- # VoltLog
2
-
3
- #### Structured logger for real-time infrastructure
4
-
5
- [![npm version](https://img.shields.io/npm/v/voltlog-io?color=blue)](https://www.npmjs.com/package/voltlog-io)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
- [![Build & Test](https://github.com/rohittiwari-dev/voltlog-io/actions/workflows/ci.yml/badge.svg)](https://github.com/rohittiwari-dev/voltlog-io/actions)
8
-
9
- **VoltLog** is a modern, lightweight, and type-safe structured logger designed specifically for high-throughput, real-time systems like IoT platforms, WebSocket servers (OCPP), and microservices.
10
-
11
- ## 📚 Full Documentation
12
-
13
- For detailed guides, API reference, and advanced usage, please visit:
14
-
15
- ### [👉 https://ocpp-ws-io.rohittiwari.me/docs/voltlog-io](https://ocpp-ws-io.rohittiwari.me/docs/voltlog-io)
16
-
17
- ---
18
-
19
- ## ✨ Key Features
20
-
21
- - **🚀 Zero-Dependency Core**: Lightweight and fast.
22
- - **🔒 Secure**: Built-in redaction for sensitive data.
23
- - **📊 High-Throughput**: Intelligent sampling for cost control.
24
- - **⚡ Developer Friendly**: Beautiful pretty printing for local dev.
25
- - **🔌 Flexible**: Works in Node.js, Bun, Deno, and Browsers.
26
-
27
- ## 📦 Installation
28
-
29
- ```bash
30
- npm install voltlog-io
31
- ```
32
-
33
- ## 🚀 Quick Start
34
-
35
- ```ts
36
- import { createLogger, consoleTransport } from "voltlog-io";
37
-
38
- const logger = createLogger({
39
- level: "INFO",
40
- transports: [consoleTransport()],
41
- });
42
-
43
- logger.info("Server started", { port: 3000, env: "production" });
44
- ```
45
-
46
- ### Local Development
47
-
48
- For readable, colored logs during development:
49
-
50
- ```ts
51
- import { createLogger, prettyTransport } from "voltlog-io";
52
-
53
- const logger = createLogger({
54
- level: "DEBUG",
55
- transports: [prettyTransport({ colorize: true })],
56
- });
57
- ```
58
-
59
- ## 🤝 Contributing
60
-
61
- Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md).
62
-
63
- ## License
64
-
65
- [MIT](LICENSE) © [Rohit Tiwari](https://github.com/rohittiwari-dev)
1
+ # VoltLog
2
+
3
+ #### Structured logger for real-time infrastructure — zero dependencies, type-safe, OCPP-aware
4
+
5
+ [![npm version](https://img.shields.io/npm/v/voltlog-io?color=blue)](https://www.npmjs.com/package/voltlog-io)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![Build & Test](https://github.com/rohittiwari-dev/voltlog-io/actions/workflows/ci.yml/badge.svg)](https://github.com/rohittiwari-dev/voltlog-io/actions)
8
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)](https://www.npmjs.com/package/voltlog-io)
9
+
10
+ **VoltLog** is a modern, lightweight, and type-safe structured logger designed for high-throughput, real-time systems like IoT platforms, WebSocket servers (OCPP), and microservices.
11
+
12
+ ## 📚 Full Documentation
13
+
14
+ For detailed guides, API reference, and advanced usage:
15
+
16
+ ### [👉 https://ocpp-ws-io.rohittiwari.me/docs/voltlog-io](https://ocpp-ws-io.rohittiwari.me/docs/voltlog-io)
17
+
18
+ ---
19
+
20
+ ## ✨ Why VoltLog?
21
+
22
+ | Feature | Pino | Winston | VoltLog |
23
+ | ------------------------- | ------------ | ------------- | ------------- |
24
+ | Zero dependencies | (11 deps) | (10+ deps) | ✅ **0 deps** |
25
+ | Type-safe generics | ❌ | ❌ | ✅ |
26
+ | Middleware pipeline | ❌ | ❌ | ✅ |
27
+ | Built-in redaction | Plugin | ❌ | ✅ |
28
+ | Sampling / rate-limit | ❌ | ❌ | ✅ |
29
+ | Alert rules | ❌ | ❌ | ✅ |
30
+ | Error cause chain | ❌ | ❌ | ✅ |
31
+ | Ring buffer | ❌ | ❌ | ✅ |
32
+ | OCPP-aware | ❌ | ❌ | ✅ |
33
+ | OpenTelemetry | Plugin | Plugin | ✅ Built-in |
34
+ | File rotation (date+size) | Plugin | Plugin | ✅ Built-in |
35
+ | HTTP request logging | Plugin | Plugin | ✅ Built-in |
36
+ | AsyncLocalStorage context | ❌ | ❌ | ✅ Built-in |
37
+
38
+ ## 📦 Installation
39
+
40
+ ```bash
41
+ npm install voltlog-io
42
+ ```
43
+
44
+ ## 🚀 Quick Start
45
+
46
+ ```ts
47
+ import { createLogger, prettyTransport, consoleTransport } from "voltlog-io";
48
+
49
+ // Development — pretty colored output
50
+ const logger = createLogger({
51
+ level: "DEBUG",
52
+ transports: [prettyTransport()],
53
+ });
54
+
55
+ // Production structured JSON
56
+ const logger = createLogger({
57
+ level: "INFO",
58
+ transports: [consoleTransport()],
59
+ });
60
+
61
+ logger.info("Server started", { port: 3000, env: "production" });
62
+ logger.error("Connection failed", new Error("ETIMEDOUT"));
63
+ ```
64
+
65
+ ## 📖 Features
66
+
67
+ ### Core Logging
68
+
69
+ ```ts
70
+ // All log levels
71
+ logger.trace("Entering function");
72
+ logger.debug("Parsed payload", { bytes: 1024 });
73
+ logger.info("User authenticated", { userId: "u-42" });
74
+ logger.warn("Rate limit approaching", { rate: 95 });
75
+ logger.error("Query failed", { query: "SELECT *" }, new Error("timeout"));
76
+ logger.fatal("Unrecoverable", new Error("OOM"));
77
+
78
+ // Runtime level control
79
+ logger.setLevel("WARN"); // change at runtime
80
+ logger.getLevel(); // → "WARN"
81
+ logger.isLevelEnabled("DEBUG"); // → false (useful to guard expensive computation)
82
+
83
+ // Timer helper — auto-logs duration
84
+ const timer = logger.startTimer();
85
+ await doExpensiveWork();
86
+ timer.done("Work completed", { items: 100 });
87
+ // → INFO Work completed { durationMs: 342, items: 100 }
88
+ ```
89
+
90
+ ### Child Loggers
91
+
92
+ ```ts
93
+ const cpLogger = logger.child({ chargePointId: "CP-101" });
94
+ cpLogger.info("Connected");
95
+ // → context: { chargePointId: "CP-101" }
96
+
97
+ const sessionLogger = cpLogger.child({ sessionId: "sess-xyz" });
98
+ sessionLogger.info("Charging started");
99
+ // → context: { chargePointId: "CP-101", sessionId: "sess-xyz" }
100
+ ```
101
+
102
+ ### Error Cause Chain (ES2022)
103
+
104
+ ```ts
105
+ const rootCause = new Error("ECONNREFUSED 10.0.0.5:5432");
106
+ const dbError = new Error("DB connection failed", { cause: rootCause });
107
+ const appError = new Error("Request failed", { cause: dbError });
108
+
109
+ logger.error("Handler crashed", appError);
110
+ // → error.cause.cause.message = "ECONNREFUSED 10.0.0.5:5432" ← root cause preserved!
111
+ ```
112
+
113
+ ### Custom ID Generator
114
+
115
+ ```ts
116
+ // Default: crypto.randomUUID() (fast, native)
117
+ const logger = createLogger({ transports: [...] });
118
+
119
+ // Custom generator
120
+ const logger = createLogger({
121
+ idGenerator: () => `log-${Date.now()}-${Math.random().toString(36).slice(2)}`,
122
+ transports: [...],
123
+ });
124
+
125
+ // Disable for max performance
126
+ const logger = createLogger({ idGenerator: false, transports: [...] });
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 🔌 Transports (14 Built-in)
132
+
133
+ ### Console & Pretty
134
+
135
+ ```ts
136
+ import { consoleTransport, prettyTransport } from "voltlog-io";
137
+
138
+ consoleTransport(); // JSON to stdout
139
+ prettyTransport({ colors: true, timestamps: true }); // colored dev output
140
+ ```
141
+
142
+ ### File (Daily + Size Rotation)
143
+
144
+ ```ts
145
+ import { fileTransport } from "voltlog-io";
146
+
147
+ fileTransport({
148
+ dir: "./logs",
149
+ filename: "app-%DATE%.log", // daily rotation
150
+ maxSize: 10_000_000, // 10MB size rotation
151
+ });
152
+ // → logs/app-2026-02-28.log → logs/app-2026-02-28.1.log (at 10MB)
153
+ ```
154
+
155
+ ### Ring Buffer (In-Memory Diagnostics)
156
+
157
+ ```ts
158
+ import { ringBufferTransport } from "voltlog-io";
159
+
160
+ const ring = ringBufferTransport({ maxSize: 500 });
161
+
162
+ // Query buffered logs
163
+ ring.getEntries({ level: "ERROR" });
164
+ ring.getEntries({ since: Date.now() - 300_000, limit: 20 });
165
+ ring.clear();
166
+ ```
167
+
168
+ ### Webhook (with Batching & Retry)
169
+
170
+ ```ts
171
+ import { webhookTransport, batchTransport } from "voltlog-io";
172
+
173
+ batchTransport(
174
+ webhookTransport({
175
+ url: "https://api.example.com/logs",
176
+ headers: { Authorization: "Bearer token" },
177
+ retry: true,
178
+ maxRetries: 3,
179
+ }),
180
+ { batchSize: 50, flushIntervalMs: 5000 },
181
+ );
182
+ ```
183
+
184
+ ### OpenTelemetry (SigNoz, Jaeger, Grafana)
185
+
186
+ ```ts
187
+ import { otelTransport, otelTraceMiddleware } from "voltlog-io";
188
+
189
+ const logger = createLogger({
190
+ middleware: [otelTraceMiddleware()], // auto-picks traceId/spanId
191
+ transports: [
192
+ otelTransport({
193
+ endpoint: "https://ingest.signoz.io",
194
+ headers: { "signoz-access-token": "YOUR_TOKEN" },
195
+ serviceName: "my-app",
196
+ resource: { "deployment.environment": "production" },
197
+ }),
198
+ ],
199
+ });
200
+ // Every log auto-includes traceId + spanId from active OTel spans
201
+ ```
202
+
203
+ ### Loki (Grafana)
204
+
205
+ ```ts
206
+ import { lokiTransport } from "voltlog-io";
207
+
208
+ lokiTransport({
209
+ host: "http://loki:3100",
210
+ labels: { app: "my-service", env: "prod" },
211
+ dynamicLabels: (entry) => ({ level: entry.levelName }),
212
+ includeMetadata: true, // context, error, correlationId
213
+ retry: true,
214
+ maxRetries: 3,
215
+ });
216
+ ```
217
+
218
+ ### Other Transports
219
+
220
+ ```ts
221
+ import {
222
+ datadogTransport, // Datadog Logs API
223
+ sentryTransport, // Sentry (errors + breadcrumbs)
224
+ slackTransport, // Slack webhook
225
+ discordTransport, // Discord webhook
226
+ redisTransport, // Redis Streams
227
+ jsonStreamTransport, // Node.js WritableStream
228
+ browserJsonStreamTransport, // Browser WritableStream
229
+ } from "voltlog-io";
230
+ ```
231
+
232
+ ---
233
+
234
+ ## 🧩 Middleware (13 Built-in)
235
+
236
+ ### Redaction
237
+
238
+ ```ts
239
+ import { redactionMiddleware } from "voltlog-io";
240
+
241
+ redactionMiddleware({
242
+ paths: ["password", "idToken", "authorization"],
243
+ deep: true, // search nested objects
244
+ replacement: "[REDACTED]",
245
+ });
246
+ ```
247
+
248
+ ### AsyncLocalStorage Context
249
+
250
+ ```ts
251
+ import { asyncContextMiddleware } from "voltlog-io";
252
+
253
+ const asyncCtx = asyncContextMiddleware();
254
+
255
+ const logger = createLogger({
256
+ middleware: [asyncCtx.middleware],
257
+ transports: [prettyTransport()],
258
+ });
259
+
260
+ // Set context once — propagates across all async boundaries
261
+ app.use((req, res, next) => {
262
+ asyncCtx.runInContext({ requestId: req.id, userId: req.user?.id }, next);
263
+ });
264
+
265
+ // Anywhere downstream — no child() needed
266
+ logger.info("Processing order");
267
+ // → auto-includes { requestId, userId }
268
+ ```
269
+
270
+ ### Sampling & Rate Limiting
271
+
272
+ ```ts
273
+ import { samplingMiddleware } from "voltlog-io";
274
+
275
+ samplingMiddleware({
276
+ maxPerWindow: 10, // max 10 logs per window
277
+ windowMs: 60_000, // per minute
278
+ priorityLevel: 40, // WARN+ always passes
279
+ });
280
+ ```
281
+
282
+ ### Other Middleware
283
+
284
+ ```ts
285
+ import {
286
+ correlationIdMiddleware, // auto-generate/propagate correlation IDs
287
+ alertMiddleware, // trigger alerts on error spikes
288
+ deduplicationMiddleware, // suppress repeated logs
289
+ heapUsageMiddleware, // attach memory stats
290
+ ipMiddleware, // extract client IP
291
+ userAgentMiddleware, // extract User-Agent
292
+ levelOverrideMiddleware, // dynamic level via headers
293
+ ocppMiddleware, // OCPP protocol enrichment
294
+ otelTraceMiddleware, // OpenTelemetry trace context
295
+ createHttpLogger, // HTTP request/response logging
296
+ } from "voltlog-io";
297
+ ```
298
+
299
+ ---
300
+
301
+ ## ⚡ Performance
302
+
303
+ ```ts
304
+ // Max performance mode — zero overhead for filtered logs
305
+ const logger = createLogger({
306
+ level: "WARN",
307
+ idGenerator: false, // no ID generation
308
+ transports: [consoleTransport()],
309
+ });
310
+
311
+ // These cost ~0.02μs each (100x faster than Pino for filtered logs)
312
+ logger.trace("free");
313
+ logger.debug("free");
314
+ logger.info("free");
315
+
316
+ // Only these execute
317
+ logger.warn("logged");
318
+ logger.error("logged");
319
+ ```
320
+
321
+ | Scenario | VoltLog | Pino |
322
+ | ----------------------------------------- | ------- | ------ |
323
+ | Filtered log (e.g. DEBUG when level=INFO) | ~0.02μs | ~3-5μs |
324
+ | Simple INFO with 1 transport | ~2-4μs | ~3-5μs |
325
+ | 3 middleware + 2 transports | ~8-15μs | N/A |
326
+
327
+ ## 🛡️ Graceful Shutdown
328
+
329
+ ```ts
330
+ process.on("SIGTERM", async () => {
331
+ await logger.flush(); // ensure all buffered logs are sent
332
+ await logger.close(); // release resources (file handles, connections)
333
+ process.exit(0);
334
+ });
335
+ ```
336
+
337
+ ## 🤝 Contributing
338
+
339
+ Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md).
340
+
341
+ ## License
342
+
343
+ [MIT](LICENSE) © [Rohit Tiwari](https://github.com/rohittiwari-dev)