scribelog 1.2.0 β†’ 2.1.0-beta.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.
Files changed (53) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +419 -180
  3. package/dist/adapters/express.d.ts +17 -0
  4. package/dist/adapters/express.js +56 -0
  5. package/dist/adapters/express.js.map +1 -0
  6. package/dist/adapters/fastify.d.ts +17 -0
  7. package/dist/adapters/fastify.js +81 -0
  8. package/dist/adapters/fastify.js.map +1 -0
  9. package/dist/adapters/koa.d.ts +17 -0
  10. package/dist/adapters/koa.js +74 -0
  11. package/dist/adapters/koa.js.map +1 -0
  12. package/dist/adapters/nest.d.ts +16 -0
  13. package/dist/adapters/nest.js +78 -0
  14. package/dist/adapters/nest.js.map +1 -0
  15. package/dist/adapters/next.d.ts +14 -0
  16. package/dist/adapters/next.js +54 -0
  17. package/dist/adapters/next.js.map +1 -0
  18. package/dist/format.d.ts +6 -0
  19. package/dist/format.js +56 -1
  20. package/dist/format.js.map +1 -1
  21. package/dist/index.d.ts +45 -0
  22. package/dist/index.js +33 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/logger.d.ts +8 -0
  25. package/dist/logger.js +97 -1
  26. package/dist/logger.js.map +1 -1
  27. package/dist/requestContext.d.ts +10 -0
  28. package/dist/requestContext.js +33 -0
  29. package/dist/requestContext.js.map +1 -0
  30. package/dist/transports/asyncBatch.d.ts +24 -0
  31. package/dist/transports/asyncBatch.js +57 -0
  32. package/dist/transports/asyncBatch.js.map +1 -0
  33. package/dist/transports/http.d.ts +27 -0
  34. package/dist/transports/http.js +117 -0
  35. package/dist/transports/http.js.map +1 -0
  36. package/dist/transports/mongodb.d.ts +19 -0
  37. package/dist/transports/mongodb.js +51 -0
  38. package/dist/transports/mongodb.js.map +1 -0
  39. package/dist/transports/sql.d.ts +22 -0
  40. package/dist/transports/sql.js +56 -0
  41. package/dist/transports/sql.js.map +1 -0
  42. package/dist/transports/tcp.d.ts +22 -0
  43. package/dist/transports/tcp.js +111 -0
  44. package/dist/transports/tcp.js.map +1 -0
  45. package/dist/transports/udp.d.ts +18 -0
  46. package/dist/transports/udp.js +75 -0
  47. package/dist/transports/udp.js.map +1 -0
  48. package/dist/transports/websocket.d.ts +21 -0
  49. package/dist/transports/websocket.js +110 -0
  50. package/dist/transports/websocket.js.map +1 -0
  51. package/dist/types.d.ts +7 -0
  52. package/dist/types.js.map +1 -1
  53. package/package.json +75 -70
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 tolongames
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
1
+ MIT License
2
+
3
+ Copyright (c) 2025 tolongames
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
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,180 +1,419 @@
1
-
2
- # Scribelog πŸͺ΅πŸ“
3
-
4
- [![npm version](https://img.shields.io/npm/v/scribelog.svg)](https://www.npmjs.com/package/scribelog)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
- [![Build Status](https://github.com/tolongames/scribelog/actions/workflows/node.js.yml/badge.svg)](https://github.com/tolongames/scribelog/actions/workflows/node.js.yml) <!-- Zaktualizuj URL, jeΕ›li trzeba -->
7
-
8
- **Scribelog** is an advanced, highly configurable logging library for Node.js applications, written in TypeScript. It offers flexible formatting, support for multiple destinations (transports like Console and File), child loggers, automatic error catching, and printf-style interpolation, aiming for a great developer experience.
9
-
10
- ---
11
-
12
- ## ✨ Key Features
13
-
14
- **Standard & Custom Logging Levels:** Use familiar levels (`error`, `warn`, `info`, etc.) or define your own custom levels.
15
- * **Highly Flexible Formatting:** Combine powerful formatters (`simple`, `json`, `timestamp`, `metadata`, `errors`, `splat`) using a composable API (`format.combine`). Customize outputs easily, including color themes.
16
- * **Printf-Style Logging:** Use `printf`-like placeholders (`%s`, `%d`, `%j`) via `format.splat()` for easy message interpolation.
17
- * **Console Color Support:** Automatic, readable colorization for the `simple` format in TTY environments, with customizable themes.
18
- * **Multiple Transports:** Log to different destinations. Built-in `ConsoleTransport` and `FileTransport` with rotation options.
19
- * **Child Loggers:** Easily create contextual loggers (`logger.child({...})`) that inherit settings but add specific metadata (like `requestId`).
20
- * **Automatic Error Handling:** Optionally catch and log `uncaughtException` and `unhandledRejection` events, including stack traces.
21
- * **TypeScript First:** Written entirely in TypeScript for type safety and excellent editor autocompletion.
22
-
23
- ---
24
-
25
- ## πŸ“¦ Installation
26
-
27
- ```bash
28
- # Core library
29
- npm install scribelog
30
- # or
31
- yarn add scribelog
32
- # or
33
- pnpm add scribelog
34
- ```
35
-
36
- ---
37
-
38
- ## πŸš€ Quick Start
39
-
40
- Get up and running in seconds:
41
-
42
- ```ts
43
- import { createLogger, format } from 'scribelog';
44
- import chalk from 'chalk';
45
-
46
- // Logger with custom color theme and default settings
47
- const logger = createLogger({
48
- level: 'debug',
49
- format: format.combine(
50
- format.timestamp(),
51
- format.simple({
52
- colors: true,
53
- levelColors: {
54
- error: chalk.bgRed.white,
55
- warn: chalk.yellow.bold,
56
- info: chalk.green,
57
- debug: chalk.blue,
58
- },
59
- })
60
- ),
61
- });
62
-
63
- logger.info('Scribelog is ready!');
64
- logger.warn('Something seems off...', { detail: 'Cache size exceeded limit' });
65
- logger.error('An error occurred!', { error: new Error('Test error') });
66
- ```
67
-
68
- **Default Console Output (example):**
69
-
70
- ```bash
71
- 2025-05-01T12:00:00.123Z [INFO]: Scribelog is ready!
72
- 2025-05-01T12:00:00.125Z [WARN]: Something seems off... { detail: 'Cache size exceeded limit' }
73
- 2025-05-01T12:00:00.127Z [ERROR]: An error occurred! { errorName: 'Error', exception: true }
74
- Error: Test error
75
- at <anonymous>:... (stack trace)
76
- ```
77
-
78
- ---
79
-
80
- ## πŸ“˜ Full Documentation
81
-
82
- This README covers the basics. For a comprehensive guide covering **all configuration options, formatters (like `json`, custom `timestamp` formats), transports (`FileTransport` with rotation), child loggers, error handling details, and advanced examples**, please see the:
83
-
84
- ➑️ **[Detailed Documentation](./DOCUMENTATION.md)** ⬅️
85
-
86
- ---
87
-
88
- ## βš™οΈ Basic Configuration (Overview)
89
-
90
- Configure your logger via `createLogger(options)`. Key options:
91
-
92
- * `level`: `'info'` (default), `'debug'`, `'warn'`, etc., or **custom levels** (e.g., `'critical'`, `'trace'`).
93
- * `format`: Use `format.combine(...)` with formatters like `format.simple()`, `format.json()`, `format.timestamp()`, `format.splat()`, `format.errors()`, `format.metadata()`. Default is `format.defaultSimpleFormat`. You can also define **custom color themes** for log levels.
94
- * `transports`: Array of `new transports.Console({...})` or `new transports.File({...})`. Default is one Console transport.
95
- * `defaultMeta`: An object with data to add to every log message.
96
- * `handleExceptions`, `handleRejections`, `exitOnError`: For automatic error catching.
97
-
98
- **Example 1: Logging JSON to a File**
99
-
100
- ```ts
101
- import { createLogger, format, transports } from 'scribelog';
102
-
103
- const fileJsonLogger = createLogger({
104
- level: 'debug',
105
- // Use the predefined JSON format (includes error handling, splat, timestamp etc.)
106
- format: format.defaultJsonFormat,
107
- transports: [
108
- new transports.File({
109
- filename: 'application.log', // Log to application.log
110
- level: 'debug', // Log debug and above to the file
111
- size: '10M', // Rotate at 10 MB
112
- maxFiles: 5 // Keep 5 rotated files
113
- })
114
- ],
115
- defaultMeta: { service: 'file-writer' }
116
- });
117
-
118
- fileJsonLogger.debug('Writing JSON log to file', { id: 1 });
119
- fileJsonLogger.error('File write error occurred', { error: new Error('Disk full'), file: 'data.txt' });
120
- ```
121
-
122
- **Example 2: Using Custom Levels and Colors**
123
-
124
- ```ts
125
- import { createLogger, format } from 'scribelog';
126
- import chalk from 'chalk';
127
-
128
- const customLevels = {
129
- critical: 0,
130
- error: 1,
131
- warn: 2,
132
- info: 3,
133
- debug: 4,
134
- trace: 5,
135
- };
136
-
137
- const logger = createLogger({
138
- levels: customLevels,
139
- level: 'trace',
140
- format: format.combine(
141
- format.timestamp(),
142
- format.simple({
143
- colors: true,
144
- levelColors: {
145
- critical: chalk.bgRed.white.bold,
146
- error: chalk.red,
147
- warn: chalk.yellow,
148
- info: chalk.green,
149
- debug: chalk.blue,
150
- trace: chalk.cyan,
151
- },
152
- })
153
- ),
154
- });
155
-
156
- logger.critical('Critical issue!');
157
- logger.trace('Trace message for debugging.');
158
- ```
159
-
160
- ---
161
-
162
- ## πŸ“š Future Work
163
-
164
- * More built-in formatters (e.g., customizable color themes).
165
- * Ability to define custom logging levels.
166
- * Improved handling of asynchronous operations in transports (especially for `exitOnError`).
167
-
168
- ---
169
-
170
- ## 🀝 Contributing
171
-
172
- Contributions are welcome! Please feel free to submit issues and pull requests on the [GitHub repository](https://github.com/tolongames/scribelog).
173
-
174
- ---
175
-
176
- ## πŸ“„ License
177
-
178
- MIT License
179
- Copyright (c) 2025 tolongames
180
- See [LICENSE](./LICENSE) for details.
1
+ # Scribelog πŸͺ΅πŸ“
2
+
3
+ [![npm version](https://img.shields.io/npm/v/scribelog.svg)](https://www.npmjs.com/package/scribelog)
4
+ [![npm downloads](https://img.shields.io/npm/dm/scribelog.svg)](https://www.npmjs.com/package/scribelog)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![Build Status](https://github.com/tolongames/scribelog/actions/workflows/node.js.yml/badge.svg)](https://github.com/tolongames/scribelog/actions/workflows/node.js.yml) <!-- Zaktualizuj URL, jeΕ›li trzeba -->
7
+
8
+ **Scribelog** is an advanced, highly configurable logging library for Node.js applications, written in TypeScript. It offers flexible formatting, support for multiple destinations (transports like Console and File), child loggers, automatic error catching, and printf-style interpolation, aiming for a great developer experience.
9
+
10
+ ---
11
+
12
+ ## ✨ Key Features
13
+
14
+ **Standard & Custom Logging Levels:** Use familiar levels (`error`, `warn`, `info`, etc.) or define your own custom levels.
15
+
16
+ - **Highly Flexible Formatting:** Combine powerful formatters (`simple`, `json`, `timestamp`, `metadata`, `errors`, `splat`) using a composable API (`format.combine`). Customize outputs easily, including color themes.
17
+ - **Printf-Style Logging:** Use `printf`-like placeholders (`%s`, `%d`, `%j`) via `format.splat()` for easy message interpolation.
18
+ - **Console Color Support:** Automatic, readable colorization for the `simple` format in TTY environments, with customizable themes.
19
+ - **Multiple Transports:** Log to different destinations. Built-in `ConsoleTransport` and `FileTransport` with rotation options.
20
+ - **Child Loggers:** Easily create contextual loggers (`logger.child({...})`) that inherit settings but add specific metadata (like `requestId`).
21
+ - **Framework adapters (Express, Koa, Fastify, NestJS, Next.js):**
22
+ Ready-to-use middleware/hooks/interceptors for request/response logging with automatic requestId (AsyncLocalStorage), duration, status, and framework tags. Minimal boilerplate.
23
+ - **Profiling & Timing:** Lightweight high-resolution timers (profile/time APIs), including sync/async helpers and start/end merging of metadata.
24
+ - **Automatic Error Handling:** Optionally catch and log `uncaughtException` and `unhandledRejection` events, including stack traces.
25
+ - **Remote Transports (HTTP, WebSocket, TCP, UDP):**
26
+ Send logs over the network to ELK/Logstash, Graylog, Datadog, or custom collectors. Supports batching (AsyncBatch) and gzip (HTTP).
27
+ - **Tagging & Context:** Add tags to log messages for easy filtering and richer context. See examples in Quick Start.
28
+ - **Asynchronous Batch Logging:** Buffer and batch log messages before sending them to a target transport to reduce I/O overhead. See examples in Basic Configuration.
29
+ - **Automatic Request/Trace ID Propagation:** Automatically attaches a request/trace ID to every log message using AsyncLocalStorage. See usage in Basic Configuration.
30
+ - **Sensitive Data Masking:** Mask sensitive fields (passwords, tokens, API keys) with the built‑in `format.maskSensitive` formatter. See usage in Basic Configuration.
31
+ - **TypeScript First:** Written entirely in TypeScript for type safety and excellent editor autocompletion.
32
+
33
+ ---
34
+
35
+ ## πŸ“¦ Installation
36
+
37
+ ```bash
38
+ # Core library
39
+ npm install scribelog
40
+ # or
41
+ yarn add scribelog
42
+ # or
43
+ pnpm add scribelog
44
+ ```
45
+
46
+ ---
47
+
48
+ ## πŸš€ Quick Start
49
+
50
+ Get up and running in seconds:
51
+
52
+ ```ts
53
+ import { createLogger, format } from 'scribelog';
54
+ import chalk from 'chalk';
55
+
56
+ // Logger with custom color theme and default settings
57
+ const logger = createLogger({
58
+ level: 'debug',
59
+ format: format.combine(
60
+ format.timestamp(),
61
+ format.simple({
62
+ colors: true,
63
+ levelColors: {
64
+ error: chalk.bgRed.white,
65
+ warn: chalk.yellow.bold,
66
+ info: chalk.green,
67
+ debug: chalk.blue,
68
+ },
69
+ })
70
+ ),
71
+ });
72
+
73
+ logger.info('Scribelog is ready!');
74
+ logger.warn('Something seems off...', { detail: 'Cache size exceeded limit' });
75
+ logger.error('An error occurred!', { error: new Error('Test error') });
76
+
77
+ // --- NEW: Logging with tags ---
78
+ logger.info('User login', { tags: ['auth', 'user'], userId: 123 });
79
+ ```
80
+
81
+ **Default Console Output (example):**
82
+
83
+ ```bash
84
+ 2025-05-01T12:00:00.123Z [INFO]: Scribelog is ready!
85
+ 2025-05-01T12:00:00.125Z [WARN]: Something seems off... { detail: 'Cache size exceeded limit' }
86
+ 2025-05-01T12:00:00.127Z [ERROR]: An error occurred! { errorName: 'Error', exception: true }
87
+ Error: Test error
88
+ at <anonymous>:... (stack trace)
89
+ 2025-05-01T12:00:00.130Z [INFO] [auth, user]: User login { userId: 123 }
90
+ ```
91
+
92
+ ## ⏱️ Profiling & Timing
93
+
94
+ Measure durations with high‑resolution timers and structured metadata. Start a timer and finish it later, or wrap sync/async blocks. Metadata passed at start is merged with metadata at end.
95
+
96
+ ```ts
97
+ // Manual start/stop
98
+ logger.profile('db');
99
+ await db.query('SELECT 1');
100
+ logger.profileEnd('db', { query: 'SELECT 1' }); // logs { profileLabel, durationMs, tags: ['profile'], ... }
101
+
102
+ // Aliases
103
+ logger.time('calc');
104
+ // ... work ...
105
+ logger.timeEnd('calc');
106
+
107
+ // Sync block
108
+ const value = logger.timeSync('compute', () => 2 + 2, { component: 'math' });
109
+
110
+ // Async block (logs success or error, rethrows on error)
111
+ await logger.timeAsync(
112
+ 'load-user',
113
+ async () => {
114
+ return await getUser(42);
115
+ },
116
+ { component: 'users' }
117
+ );
118
+ ```
119
+
120
+ Every profile entry includes:
121
+
122
+ - message: the label you provided
123
+ - metadata: profileLabel, durationMs, tags: ['profile'], and any custom fields
124
+ - requestId is attached automatically when request context is active
125
+
126
+ ---
127
+
128
+ ## πŸ“˜ Full Documentation
129
+
130
+ This README covers the basics. For a comprehensive guide covering **all configuration options, formatters (like `json`, custom `timestamp` formats), transports (`FileTransport` with rotation), child loggers, error handling details, and advanced examples**, please see the:
131
+
132
+ ➑️ **[Detailed Documentation](./DOCUMENTATION.md)** ⬅️
133
+
134
+ ---
135
+
136
+ ## βš™οΈ Basic Configuration (Overview)
137
+
138
+ Configure your logger via `createLogger(options)`. Key options:
139
+
140
+ - `level`: `'info'` (default), `'debug'`, `'warn'`, etc., or **custom levels** (e.g., `'critical'`, `'trace'`).
141
+ - `format`: Use `format.combine(...)` with formatters like `format.simple()`, `format.json()`, `format.timestamp()`, `format.splat()`, `format.errors()`, `format.metadata()`. Default is `format.defaultSimpleFormat`. You can also define **custom color themes** for log levels.
142
+ - `transports`: Array of `new transports.Console({...})` or `new transports.File({...})`. Default is one Console transport.
143
+ - `defaultMeta`: An object with data to add to every log message.
144
+ - `handleExceptions`, `handleRejections`, `exitOnError`: For automatic error catching.
145
+
146
+ **Example 1: Logging JSON to a File**
147
+
148
+ ```ts
149
+ import { createLogger, format, transports } from 'scribelog';
150
+
151
+ const fileJsonLogger = createLogger({
152
+ level: 'debug',
153
+ // Use the predefined JSON format (includes error handling, splat, timestamp etc.)
154
+ format: format.defaultJsonFormat,
155
+ transports: [
156
+ new transports.File({
157
+ filename: 'application.log', // Log to application.log
158
+ level: 'debug', // Log debug and above to the file
159
+ size: '10M', // Rotate at 10 MB
160
+ maxFiles: 5, // Keep 5 rotated files
161
+ }),
162
+ ],
163
+ defaultMeta: { service: 'file-writer' },
164
+ });
165
+
166
+ fileJsonLogger.debug('Writing JSON log to file', { id: 1 });
167
+ fileJsonLogger.error('File write error occurred', {
168
+ error: new Error('Disk full'),
169
+ file: 'data.txt',
170
+ });
171
+ ```
172
+
173
+ **Example 2: Using Custom Levels and Colors**
174
+
175
+ ```ts
176
+ import { createLogger, format } from 'scribelog';
177
+ import chalk from 'chalk';
178
+
179
+ const customLevels = {
180
+ critical: 0,
181
+ error: 1,
182
+ warn: 2,
183
+ info: 3,
184
+ debug: 4,
185
+ trace: 5,
186
+ };
187
+
188
+ const logger = createLogger({
189
+ levels: customLevels,
190
+ level: 'trace',
191
+ format: format.combine(
192
+ format.timestamp(),
193
+ format.simple({
194
+ colors: true,
195
+ levelColors: {
196
+ critical: chalk.bgRed.white.bold,
197
+ error: chalk.red,
198
+ warn: chalk.yellow,
199
+ info: chalk.green,
200
+ debug: chalk.blue,
201
+ trace: chalk.cyan,
202
+ },
203
+ })
204
+ ),
205
+ });
206
+
207
+ logger.critical('Critical issue!');
208
+ logger.trace('Trace message for debugging.');
209
+ ```
210
+
211
+ **Example 3: Batching logs (AsyncBatch)**
212
+
213
+ ```ts
214
+ import { createLogger, transports } from 'scribelog';
215
+
216
+ const fileTransport = new transports.File({ filename: 'batched.log' });
217
+
218
+ const asyncBatch = new transports.AsyncBatch({
219
+ target: fileTransport,
220
+ batchSize: 5, // Send logs in batches of 5
221
+ flushIntervalMs: 2000, // Or every 2 seconds
222
+ });
223
+
224
+ const logger = createLogger({ transports: [asyncBatch] });
225
+
226
+ logger.info('First log');
227
+ logger.info('Second log');
228
+ // ...more logs
229
+ ```
230
+
231
+ **Example 4: Request/Trace ID propagation**
232
+
233
+ ```ts
234
+ import { runWithRequestContext, setRequestId, createLogger } from 'scribelog';
235
+ const logger = createLogger();
236
+
237
+ // In your middleware:
238
+ app.use((req, res, next) => {
239
+ const reqId = req.headers['x-request-id'] || generateRandomId();
240
+ runWithRequestContext({ requestId: String(reqId) }, () => {
241
+ next();
242
+ });
243
+ });
244
+
245
+ // Anywhere later in the same async flow:
246
+ logger.info('Handled request'); // requestId is attached automatically
247
+ ```
248
+
249
+ **Example 5: Sensitive data masking**
250
+
251
+ ```ts
252
+ import { createLogger, format } from 'scribelog';
253
+
254
+ const logger = createLogger({
255
+ format: format.combine(
256
+ format.maskSensitive(['password', 'token', 'apiKey']),
257
+ format.simple()
258
+ ),
259
+ });
260
+
261
+ logger.info('User login', {
262
+ username: 'bob',
263
+ password: 'sekret123',
264
+ token: 'abc',
265
+ profile: { apiKey: 'xyz' },
266
+ });
267
+ // Output (example): password: '***', token: '***', profile: { apiKey: '***' }
268
+ ```
269
+
270
+ ## Framework adapters (quick integration)
271
+
272
+ Express:
273
+
274
+ ```ts
275
+ import express from 'express';
276
+ import { createLogger, adapters } from 'scribelog';
277
+
278
+ const app = express();
279
+ const logger = createLogger();
280
+ app.use(adapters.express.createMiddleware({ logger }));
281
+ ```
282
+
283
+ Koa:
284
+
285
+ ```ts
286
+ import Koa from 'koa';
287
+ import { createLogger, adapters } from 'scribelog';
288
+
289
+ const app = new Koa();
290
+ const logger = createLogger();
291
+ app.use(adapters.koa.createMiddleware({ logger }));
292
+ ```
293
+
294
+ Fastify:
295
+
296
+ ```ts
297
+ import Fastify from 'fastify';
298
+ import { createLogger, adapters } from 'scribelog';
299
+
300
+ const app = Fastify();
301
+ const logger = createLogger();
302
+ const register = adapters.fastify.createPlugin({ logger });
303
+ register(app);
304
+ ```
305
+
306
+ NestJS (global interceptor):
307
+
308
+ ```ts
309
+ import { adapters, createLogger } from 'scribelog';
310
+ const app = await NestFactory.create(AppModule);
311
+ const logger = createLogger();
312
+ app.useGlobalInterceptors(adapters.nest.createInterceptor({ logger }));
313
+ ```
314
+
315
+ Next.js (API Route):
316
+
317
+ ```ts
318
+ import { adapters, createLogger } from 'scribelog';
319
+ const logger = createLogger();
320
+ export default adapters.next.createApiHandler(
321
+ async (req, res) => {
322
+ res.statusCode = 200;
323
+ res.end('OK');
324
+ },
325
+ { logger }
326
+ );
327
+ ```
328
+
329
+ ## Remote transports (network logging)
330
+
331
+ HTTP (+ batching + gzip):
332
+
333
+ ```ts
334
+ import { createLogger, transports, format } from 'scribelog';
335
+
336
+ const httpT = new transports.Http({
337
+ url: 'https://logs.example.com/ingest',
338
+ headers: { 'x-api-key': 'your-key' },
339
+ compress: true, // gzip the body
340
+ timeoutMs: 8000,
341
+ // format defaults to format.defaultJsonFormat if not provided
342
+ });
343
+
344
+ const batched = new transports.AsyncBatch({
345
+ target: httpT,
346
+ batchSize: 20,
347
+ flushIntervalMs: 1000,
348
+ });
349
+
350
+ const logger = createLogger({
351
+ transports: [batched],
352
+ format: format.defaultJsonFormat,
353
+ });
354
+ logger.info('Remote log', { service: 'api' });
355
+ ```
356
+
357
+ WebSocket (requires ws: npm i ws):
358
+
359
+ ```ts
360
+ import { createLogger, transports } from 'scribelog';
361
+
362
+ const wsT = new transports.WebSocket({ url: 'wss://logs.example.com/stream' });
363
+ const logger = createLogger({ transports: [wsT] });
364
+ logger.error('Streamed error', { code: 500 });
365
+ ```
366
+
367
+ TCP (newline-delimited JSON) + batching:
368
+
369
+ ```ts
370
+ import { createLogger, transports } from 'scribelog';
371
+
372
+ const tcp = new transports.Tcp({ host: '127.0.0.1', port: 5000 });
373
+ const batched = new transports.AsyncBatch({
374
+ target: tcp,
375
+ batchSize: 50,
376
+ flushIntervalMs: 500,
377
+ });
378
+ const logger = createLogger({ transports: [batched] });
379
+ logger.info('Hello over TCP', { env: 'prod' });
380
+ ```
381
+
382
+ UDP (best-effort, e.g., GELF-like):
383
+
384
+ ```ts
385
+ import { createLogger, transports } from 'scribelog';
386
+
387
+ const udp = new transports.Udp({ host: '127.0.0.1', port: 12201 });
388
+ const logger = createLogger({ transports: [udp] });
389
+ logger.warn('Warning via UDP');
390
+ ```
391
+
392
+ Notes:
393
+
394
+ - Prefer JSON format for collectors: use format.defaultJsonFormat.
395
+ - Use AsyncBatch to reduce network overhead and smooth bursts.
396
+ - Redact secrets before sending: format.maskSensitive([...]).
397
+ - requestId from async context is automatically attached to logs.
398
+
399
+ ---
400
+
401
+ ## πŸ“š Future Work
402
+
403
+ - Syslog/journald transports for system logging
404
+ - OpenTelemetry integration (trace/span IDs propagation)
405
+ - More adapters and richer redaction/masking presets
406
+
407
+ ---
408
+
409
+ ## 🀝 Contributing
410
+
411
+ Contributions are welcome! Please feel free to submit issues and pull requests on the [GitHub repository](https://github.com/tolongames/scribelog).
412
+
413
+ ---
414
+
415
+ ## πŸ“„ License
416
+
417
+ MIT License
418
+ Copyright (c) 2025 tolongames
419
+ See [LICENSE](./LICENSE) for details.
@@ -0,0 +1,17 @@
1
+ import type { LoggerInterface, LogLevel } from '../types';
2
+ export interface ExpressLoggerOptions {
3
+ logger?: LoggerInterface;
4
+ headerName?: string;
5
+ generateId?: () => string;
6
+ redactHeaders?: string[];
7
+ logRequest?: boolean;
8
+ logResponse?: boolean;
9
+ levelRequest?: LogLevel;
10
+ levelResponse?: LogLevel;
11
+ tags?: string[];
12
+ maxHeaderValueLength?: number;
13
+ }
14
+ /**
15
+ * Express middleware: automatyczne ustawienie requestId + logi start/stop.
16
+ */
17
+ export declare function createExpressMiddleware(opts?: ExpressLoggerOptions): (req: any, res: any, next: any) => void;