@push.rocks/smartlog 3.1.8 → 3.1.9

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.
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartlog',
6
- version: '3.1.8',
6
+ version: '3.1.9',
7
7
  description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.'
8
8
  };
9
9
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMDBfY29tbWl0aW5mb19kYXRhLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvMDBfY29tbWl0aW5mb19kYXRhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHO0lBQ3hCLElBQUksRUFBRSxzQkFBc0I7SUFDNUIsT0FBTyxFQUFFLE9BQU87SUFDaEIsV0FBVyxFQUFFLGlHQUFpRztDQUMvRyxDQUFBIn0=
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/smartlog",
3
- "version": "3.1.8",
3
+ "version": "3.1.9",
4
4
  "private": false,
5
5
  "description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
6
6
  "keywords": [
package/readme.md CHANGED
@@ -1,288 +1,736 @@
1
- # @push.rocks/smartlog
1
+ # @push.rocks/smartlog 🚀
2
+ *The ultimate TypeScript logging solution for modern applications*
2
3
 
3
- Minimalistic distributed and extensible logging tool for TypeScript and JavaScript applications.
4
+ [![npm version](https://img.shields.io/npm/v/@push.rocks/smartlog.svg)](https://www.npmjs.com/package/@push.rocks/smartlog)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
6
 
5
- ## Install
7
+ > **smartlog** is a powerful, distributed, and extensible logging system designed for the cloud-native era. Whether you're debugging locally, monitoring production systems, or building complex microservices, smartlog adapts to your needs with style. 🎯
6
8
 
7
- Install `@push.rocks/smartlog` using pnpm (recommended), npm, or yarn:
9
+ ## 🌟 Why smartlog?
8
10
 
9
- ```sh
11
+ - **🎨 Beautiful Console Output**: Color-coded, formatted logs that are actually readable
12
+ - **🔌 Extensible Architecture**: Plug in any destination - databases, files, remote servers
13
+ - **🌍 Distributed by Design**: Built for microservices with correlation and context tracking
14
+ - **⚡ Zero-Config Start**: Works out of the box, scales when you need it
15
+ - **🎭 Interactive CLI Tools**: Spinners and progress bars that handle non-TTY environments gracefully
16
+ - **📊 Structured Logging**: JSON-based for easy parsing and analysis
17
+ - **🔍 Smart Filtering**: Log levels and context-based filtering
18
+
19
+ ## 📦 Installation
20
+
21
+ ```bash
10
22
  # Using pnpm (recommended)
11
23
  pnpm add @push.rocks/smartlog
12
24
 
13
25
  # Using npm
14
- npm install @push.rocks/smartlog --save
26
+ npm install @push.rocks/smartlog
15
27
 
16
28
  # Using yarn
17
29
  yarn add @push.rocks/smartlog
18
30
  ```
19
31
 
20
- Ensure you have TypeScript and Node.js installed for TypeScript projects.
32
+ ## 🚀 Quick Start
21
33
 
22
- ## Package Exports
34
+ ### Your First Logger
23
35
 
24
- The package provides the following exports:
36
+ ```typescript
37
+ import { Smartlog } from '@push.rocks/smartlog';
25
38
 
26
- ```javascript
27
- // Main module
28
- import { Smartlog, LogGroup, ConsoleLog } from '@push.rocks/smartlog';
39
+ // Create a logger with context
40
+ const logger = new Smartlog({
41
+ logContext: {
42
+ company: 'MyStartup',
43
+ companyunit: 'Backend Team',
44
+ containerName: 'api-gateway',
45
+ environment: 'production',
46
+ runtime: 'node',
47
+ zone: 'eu-central'
48
+ }
49
+ });
29
50
 
30
- // Type definitions and interfaces
31
- import { ILogPackage, ILogDestination, TLogLevel } from '@push.rocks/smartlog/interfaces';
51
+ // Enable beautiful console output
52
+ logger.enableConsole();
32
53
 
33
- // Interactive console features (spinners, progress bars)
34
- import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
54
+ // Start logging!
55
+ logger.log('info', '🎉 Application started successfully');
56
+ logger.log('error', '💥 Database connection failed', {
57
+ errorCode: 'DB_TIMEOUT',
58
+ attemptCount: 3
59
+ });
60
+ ```
35
61
 
36
- // Context management
37
- import { ... } from '@push.rocks/smartlog/context';
62
+ ### Using the Default Logger
38
63
 
39
- // Log destinations
40
- import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
41
- import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
42
- import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
43
- import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
44
- import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
64
+ For quick prototyping and simple applications:
65
+
66
+ ```typescript
67
+ import { defaultLogger } from '@push.rocks/smartlog';
68
+
69
+ defaultLogger.log('info', 'This is so easy!');
70
+ ```
71
+
72
+ ## 📚 Core Concepts
73
+
74
+ ### Log Levels
75
+
76
+ smartlog supports semantic log levels for different scenarios:
77
+
78
+ ```typescript
79
+ // Lifecycle events
80
+ logger.log('lifecycle', '🔄 Container starting up...');
45
81
 
46
- // Receiver functionality
47
- import { SmartlogReceiver } from '@push.rocks/smartlog/receiver';
82
+ // Success states
83
+ logger.log('success', '✅ Payment processed');
84
+ logger.log('ok', '👍 Health check passed');
85
+
86
+ // Information and debugging
87
+ logger.log('info', '📋 User profile updated');
88
+ logger.log('note', '📌 Cache invalidated');
89
+ logger.log('debug', '🔍 Query execution plan', { sql: 'SELECT * FROM users' });
90
+
91
+ // Warnings and errors
92
+ logger.log('warn', '⚠️ Memory usage above 80%');
93
+ logger.log('error', '❌ Failed to send email');
94
+
95
+ // Verbose output
96
+ logger.log('silly', '🔬 Entering function processPayment()');
97
+ ```
98
+
99
+ ### Log Groups for Correlation
100
+
101
+ Perfect for tracking request flows through your system:
102
+
103
+ ```typescript
104
+ // Track a user request through multiple operations
105
+ const requestGroup = logger.createLogGroup('req-7f3a2b');
106
+
107
+ requestGroup.log('info', 'Received POST /api/users');
108
+ requestGroup.log('debug', 'Validating request body');
109
+ requestGroup.log('info', 'Creating user in database');
110
+ requestGroup.log('success', 'User created successfully', { userId: 'usr_123' });
111
+
112
+ // All logs in the group share the same correlation ID
48
113
  ```
49
114
 
50
- ## Usage
115
+ ## 🎯 Log Destinations
51
116
 
52
- `@push.rocks/smartlog` is a flexible, extensible logging tool designed for distributed systems. It provides a consistent logging interface across different environments while being lightweight and customizable.
117
+ ### Built-in Destinations
53
118
 
54
- ### Creating a Logger Instance
119
+ #### 🖥️ Local Console (Enhanced)
55
120
 
56
- Start by importing `Smartlog` and create a logger instance:
121
+ Beautiful, colored output for local development:
57
122
 
58
123
  ```typescript
59
- import { Smartlog } from '@push.rocks/smartlog';
124
+ import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
60
125
 
61
- const logger = new Smartlog({
62
- logContext: {
63
- company: 'My Company',
64
- companyunit: 'Cloud Team',
65
- containerName: 'api-service',
66
- environment: 'production', // 'local', 'test', 'staging', 'production'
67
- runtime: 'node', // 'node', 'chrome', 'rust', 'deno', 'cloudflare_workers'
68
- zone: 'us-west',
69
- },
70
- minimumLogLevel: 'info', // Optional, defaults to 'silly'
126
+ const localDestination = new DestinationLocal({
127
+ logLevel: 'debug' // Optional: filter by minimum log level
71
128
  });
72
129
 
73
- // Enable console output
74
- logger.enableConsole();
130
+ logger.addLogDestination(localDestination);
75
131
  ```
76
132
 
77
- The context enriches logs with valuable information for filtering and analysis across distributed systems.
133
+ #### 📁 File Logging
78
134
 
79
- ### Logging Messages
135
+ Persist logs to files with automatic rotation support:
80
136
 
81
137
  ```typescript
82
- // Basic logging
83
- logger.log('info', 'User authenticated successfully');
84
- logger.log('error', 'Database connection failed', { errorCode: 'DB_CONN_ERR', retryCount: 3 });
85
- logger.log('warn', 'Rate limit approaching', { currentRate: 95, limit: 100 });
138
+ import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
86
139
 
87
- // Log levels: 'silly', 'info', 'debug', 'note', 'ok', 'success', 'warn', 'error', 'lifecycle'
140
+ const fileDestination = new SmartlogDestinationFile('./logs/app.log');
141
+ logger.addLogDestination(fileDestination);
88
142
  ```
89
143
 
90
- The third parameter accepts any additional data to attach to the log entry.
144
+ #### 🌐 Browser DevTools
91
145
 
92
- ### Default Logger
146
+ Optimized for browser environments with styled console output:
93
147
 
94
- For simple cases, use the built-in default logger:
148
+ ```typescript
149
+ import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
150
+
151
+ const devtools = new SmartlogDestinationDevtools();
152
+ logger.addLogDestination(devtools);
153
+ ```
154
+
155
+ #### 📊 ClickHouse Analytics
156
+
157
+ Store logs in ClickHouse for powerful analytics:
95
158
 
96
159
  ```typescript
97
- import { defaultLogger } from '@push.rocks/smartlog';
160
+ import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
161
+
162
+ const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
163
+ host: 'analytics.example.com',
164
+ port: 8123,
165
+ database: 'logs',
166
+ user: 'logger',
167
+ password: process.env.CLICKHOUSE_PASSWORD
168
+ });
98
169
 
99
- defaultLogger.log('info', 'Application started');
170
+ logger.addLogDestination(clickhouse);
171
+
172
+ // Query your logs with SQL!
173
+ // SELECT * FROM logs WHERE level = 'error' AND timestamp > now() - INTERVAL 1 HOUR
100
174
  ```
101
175
 
102
- ### Log Groups
176
+ #### 🔗 Remote Receiver
103
177
 
104
- Group related logs for better traceability:
178
+ Send logs to a centralized logging service:
105
179
 
106
180
  ```typescript
107
- // Create a log group with optional transaction ID
108
- const requestGroup = logger.createLogGroup('tx-123456');
181
+ import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
182
+
183
+ const receiver = new SmartlogDestinationReceiver({
184
+ endpoint: 'https://logs.mycompany.com/ingest',
185
+ apiKey: process.env.LOG_API_KEY,
186
+ batchSize: 100, // Send logs in batches
187
+ flushInterval: 5000 // Flush every 5 seconds
188
+ });
109
189
 
110
- // Logs within this group will be correlated
111
- requestGroup.log('info', 'Processing payment request');
112
- requestGroup.log('debug', 'Validating payment details');
113
- requestGroup.log('success', 'Payment processed successfully');
190
+ logger.addLogDestination(receiver);
114
191
  ```
115
192
 
116
- ### Custom Log Destinations
193
+ ### 🛠️ Custom Destinations
117
194
 
118
- Extend logging capabilities by adding custom destinations:
195
+ Build your own destination for any logging backend:
119
196
 
120
197
  ```typescript
121
- import { Smartlog, ILogDestination } from '@push.rocks/smartlog';
198
+ import { ILogDestination, ILogPackage } from '@push.rocks/smartlog/interfaces';
122
199
 
123
- class DatabaseLogDestination implements ILogDestination {
124
- async handleLog(logPackage) {
125
- // Store log in database
126
- await db.logs.insert({
127
- timestamp: new Date(logPackage.timestamp),
128
- level: logPackage.level,
129
- message: logPackage.message,
130
- data: logPackage.data,
131
- context: logPackage.context
200
+ class ElasticsearchDestination implements ILogDestination {
201
+ private client: ElasticsearchClient;
202
+
203
+ constructor(config: ElasticsearchConfig) {
204
+ this.client = new ElasticsearchClient(config);
205
+ }
206
+
207
+ async handleLog(logPackage: ILogPackage): Promise<void> {
208
+ await this.client.index({
209
+ index: `logs-${new Date().toISOString().split('T')[0]}`,
210
+ body: {
211
+ '@timestamp': logPackage.timestamp,
212
+ level: logPackage.level,
213
+ message: logPackage.message,
214
+ context: logPackage.context,
215
+ data: logPackage.data,
216
+ correlation: logPackage.correlation
217
+ }
132
218
  });
133
219
  }
134
220
  }
135
221
 
136
- // Add the custom destination to your logger
137
- logger.addLogDestination(new DatabaseLogDestination());
222
+ // Use your custom destination
223
+ logger.addLogDestination(new ElasticsearchDestination({
224
+ node: 'https://elasticsearch.example.com'
225
+ }));
138
226
  ```
139
227
 
140
- ### Built-in Destinations
228
+ ## 🎨 Interactive Console Features
141
229
 
142
- SmartLog comes with several built-in destinations for various logging needs:
230
+ ### Spinners
231
+
232
+ Create beautiful loading animations that degrade gracefully in CI/CD:
143
233
 
144
234
  ```typescript
145
- // Log to a file
146
- import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
147
- logger.addLogDestination(new SmartlogDestinationFile('/path/to/logfile.log'));
235
+ import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
148
236
 
149
- // Colorful local console logging
150
- import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
151
- logger.addLogDestination(new DestinationLocal());
237
+ const spinner = new SmartlogSourceInteractive();
152
238
 
153
- // Browser DevTools with colored formatting
154
- import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
155
- logger.addLogDestination(new SmartlogDestinationDevtools());
239
+ // Basic usage
240
+ spinner.text('🔄 Fetching data from API...');
241
+ // ... perform async operation
242
+ spinner.finishSuccess('✅ Data fetched successfully!');
243
+
244
+ // Chained operations
245
+ spinner
246
+ .text('📡 Connecting to database')
247
+ .successAndNext('🔍 Running migrations')
248
+ .successAndNext('🌱 Seeding data')
249
+ .finishSuccess('🎉 Database ready!');
250
+
251
+ // Customize appearance
252
+ spinner
253
+ .setSpinnerStyle('dots') // dots, line, star, simple
254
+ .setColor('cyan') // any terminal color
255
+ .setSpeed(80) // animation speed in ms
256
+ .text('🚀 Deploying application...');
257
+
258
+ // Handle failures
259
+ try {
260
+ await deployApp();
261
+ spinner.finishSuccess('✅ Deployed!');
262
+ } catch (error) {
263
+ spinner.finishFail('❌ Deployment failed');
264
+ }
265
+ ```
266
+
267
+ ### Progress Bars
268
+
269
+ Track long-running operations with style:
270
+
271
+ ```typescript
272
+ import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
273
+
274
+ // Create a progress bar
275
+ const progress = new SmartlogProgressBar({
276
+ total: 100,
277
+ width: 40,
278
+ complete: '█',
279
+ incomplete: '░',
280
+ showEta: true,
281
+ showPercent: true,
282
+ showCount: true
283
+ });
284
+
285
+ // Update progress
286
+ for (let i = 0; i <= 100; i++) {
287
+ progress.update(i);
288
+ await someAsyncWork();
289
+ }
290
+
291
+ progress.complete();
292
+
293
+ // Real-world example: Processing files
294
+ const files = await getFiles();
295
+ const progress = new SmartlogProgressBar({
296
+ total: files.length,
297
+ width: 50
298
+ });
299
+
300
+ for (const [index, file] of files.entries()) {
301
+ await processFile(file);
302
+ progress.increment(); // or progress.update(index + 1)
303
+ }
304
+ ```
305
+
306
+ ### Non-Interactive Fallback
307
+
308
+ Both spinners and progress bars automatically detect non-interactive environments (CI/CD, Docker logs, piped output) and fallback to simple text output:
309
+
310
+ ```
311
+ [Loading] Connecting to database
312
+ [Success] Connected to database
313
+ [Loading] Running migrations
314
+ Progress: 25% (25/100)
315
+ Progress: 50% (50/100)
316
+ Progress: 100% (100/100)
317
+ [Success] Migrations complete
318
+ ```
319
+
320
+ ## 🔧 Advanced Features
321
+
322
+ ### Context Management
323
+
324
+ Add context that flows through your entire application:
325
+
326
+ ```typescript
327
+ // Set global context
328
+ logger.addLogContext({
329
+ requestId: 'req-123',
330
+ userId: 'user-456',
331
+ feature: 'payment-processing'
332
+ });
333
+
334
+ // All subsequent logs include this context
335
+ logger.log('info', 'Processing payment');
336
+ // Output includes: { ...context, message: 'Processing payment' }
337
+ ```
156
338
 
157
- // ClickHouse database logging
339
+ ### Scoped Logging
340
+
341
+ Create scoped loggers for different components:
342
+
343
+ ```typescript
344
+ const dbLogger = logger.createScope('database');
345
+ const apiLogger = logger.createScope('api');
346
+
347
+ dbLogger.log('info', 'Executing query');
348
+ apiLogger.log('info', 'Handling request');
349
+ // Logs include scope information for filtering
350
+ ```
351
+
352
+ ### Minimum Log Levels
353
+
354
+ Control log verbosity per environment:
355
+
356
+ ```typescript
357
+ const logger = new Smartlog({
358
+ logContext: { environment: 'production' },
359
+ minimumLogLevel: 'warn' // Only warn and above in production
360
+ });
361
+
362
+ // These won't be logged in production
363
+ logger.log('debug', 'Detailed debug info');
364
+ logger.log('info', 'Regular info');
365
+
366
+ // These will be logged
367
+ logger.log('warn', 'Warning message');
368
+ logger.log('error', 'Error message');
369
+ ```
370
+
371
+ ### Increment Logging
372
+
373
+ Perfect for metrics and counters:
374
+
375
+ ```typescript
376
+ // Track API calls
377
+ logger.increment('info', 'api.requests', { endpoint: '/users', method: 'GET' });
378
+ logger.increment('info', 'api.requests', { endpoint: '/users', method: 'POST' });
379
+
380
+ // Track errors by type
381
+ logger.increment('error', 'payment.failed', { reason: 'insufficient_funds' });
382
+ logger.increment('error', 'payment.failed', { reason: 'card_declined' });
383
+ ```
384
+
385
+ ### Capture All Console Output
386
+
387
+ Redirect all console.log and console.error through smartlog:
388
+
389
+ ```typescript
390
+ logger.enableConsole({
391
+ captureAll: true // Capture all console.* methods
392
+ });
393
+
394
+ console.log('This goes through smartlog!');
395
+ console.error('This too!');
396
+ // All console output is now structured and routed through your destinations
397
+ ```
398
+
399
+ ## 🏗️ Real-World Examples
400
+
401
+ ### Microservice with Distributed Tracing
402
+
403
+ ```typescript
404
+ import { Smartlog } from '@push.rocks/smartlog';
158
405
  import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
406
+
407
+ // Initialize logger with service context
408
+ const logger = new Smartlog({
409
+ logContext: {
410
+ company: 'TechCorp',
411
+ companyunit: 'Platform',
412
+ containerName: 'user-service',
413
+ environment: process.env.NODE_ENV,
414
+ runtime: 'node',
415
+ zone: process.env.CLOUD_ZONE
416
+ }
417
+ });
418
+
419
+ // Add ClickHouse for analytics
159
420
  const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
160
- host: 'clickhouse.example.com',
161
- port: 8123,
162
- user: 'username',
163
- password: 'password',
164
- database: 'logs_db'
421
+ host: process.env.CLICKHOUSE_HOST,
422
+ database: 'microservices_logs'
165
423
  });
166
424
  logger.addLogDestination(clickhouse);
167
425
 
168
- // Remote receiver logging
169
- import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
170
- logger.addLogDestination(new SmartlogDestinationReceiver({
171
- endpoint: 'https://logs.example.com/api/logs'
172
- }));
173
- ```
426
+ // Enable local console for development
427
+ if (process.env.NODE_ENV === 'development') {
428
+ logger.enableConsole();
429
+ }
174
430
 
175
- ### Interactive Console Features
431
+ // Express middleware for request tracking
432
+ app.use((req, res, next) => {
433
+ const requestId = generateRequestId();
434
+ const logGroup = logger.createLogGroup(requestId);
435
+
436
+ // Attach logger to request
437
+ req.logger = logGroup;
438
+
439
+ // Log request
440
+ logGroup.log('info', 'Incoming request', {
441
+ method: req.method,
442
+ path: req.path,
443
+ ip: req.ip
444
+ });
445
+
446
+ // Track response
447
+ res.on('finish', () => {
448
+ logGroup.log('info', 'Request completed', {
449
+ statusCode: res.statusCode,
450
+ duration: Date.now() - req.startTime
451
+ });
452
+ });
453
+
454
+ next();
455
+ });
456
+ ```
176
457
 
177
- For CLI applications, use the interactive console features:
458
+ ### CLI Tool with Progress Tracking
178
459
 
179
460
  ```typescript
461
+ import { Smartlog } from '@push.rocks/smartlog';
180
462
  import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
463
+
464
+ const logger = new Smartlog({
465
+ logContext: {
466
+ containerName: 'migration-tool',
467
+ environment: 'cli'
468
+ }
469
+ });
470
+
471
+ logger.enableConsole();
472
+
473
+ async function migrateDatabase() {
474
+ const spinner = new SmartlogSourceInteractive();
475
+
476
+ // Connect to database
477
+ spinner.text('🔌 Connecting to database...');
478
+ await connectDB();
479
+ spinner.finishSuccess('✅ Connected to database');
480
+
481
+ // Get migrations
482
+ spinner.text('📋 Loading migrations...');
483
+ const migrations = await getMigrations();
484
+ spinner.finishSuccess(`✅ Found ${migrations.length} migrations`);
485
+
486
+ // Run migrations with progress bar
487
+ const progress = new SmartlogProgressBar({
488
+ total: migrations.length,
489
+ width: 40,
490
+ showEta: true
491
+ });
492
+
493
+ for (const [index, migration] of migrations.entries()) {
494
+ logger.log('info', `Running migration: ${migration.name}`);
495
+ await runMigration(migration);
496
+ progress.update(index + 1);
497
+ }
498
+
499
+ progress.complete();
500
+ logger.log('success', '🎉 All migrations completed successfully!');
501
+ }
181
502
  ```
182
503
 
183
- #### Spinners
504
+ ### Production Logging with Multiple Destinations
184
505
 
185
506
  ```typescript
186
- const spinner = new SmartlogSourceInteractive();
507
+ import { Smartlog } from '@push.rocks/smartlog';
508
+ import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
509
+ import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
510
+ import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
187
511
 
188
- // Start a spinner with text
189
- spinner.text('Loading data...');
512
+ const logger = new Smartlog({
513
+ logContext: {
514
+ company: 'Enterprise Corp',
515
+ containerName: 'payment-processor',
516
+ environment: 'production',
517
+ runtime: 'node',
518
+ zone: 'us-east-1'
519
+ },
520
+ minimumLogLevel: 'info' // No debug logs in production
521
+ });
190
522
 
191
- // Customize appearance
192
- spinner.setSpinnerStyle('dots'); // 'dots', 'line', 'star', 'simple'
193
- spinner.setColor('blue'); // 'red', 'green', 'yellow', 'blue', etc.
194
- spinner.setSpeed(80); // Animation speed in milliseconds
523
+ // Console for container logs (structured for log aggregators)
524
+ logger.addLogDestination(new DestinationLocal());
195
525
 
196
- // Update spinner status
197
- spinner.text('Processing records...');
526
+ // File for audit trail
527
+ logger.addLogDestination(new SmartlogDestinationFile('/var/log/app/audit.log'));
198
528
 
199
- // Complete with success or failure
200
- spinner.finishSuccess('Data loaded successfully!');
201
- spinner.finishFail('Failed to load data!');
529
+ // Central logging service
530
+ logger.addLogDestination(new SmartlogDestinationReceiver({
531
+ endpoint: 'https://logs.enterprise.com/ingest',
532
+ apiKey: process.env.LOG_API_KEY,
533
+ batchSize: 100,
534
+ flushInterval: 5000
535
+ }));
202
536
 
203
- // Chain operations
204
- spinner.text('Connecting to server')
205
- .successAndNext('Fetching records')
206
- .successAndNext('Processing data')
207
- .finishSuccess('All done!');
537
+ // Critical error alerts
538
+ logger.addLogDestination({
539
+ async handleLog(logPackage) {
540
+ if (logPackage.level === 'error' && logPackage.data?.critical) {
541
+ await sendAlert({
542
+ channel: 'ops-team',
543
+ message: `🚨 Critical error: ${logPackage.message}`,
544
+ data: logPackage
545
+ });
546
+ }
547
+ }
548
+ });
208
549
  ```
209
550
 
210
- #### Progress Bars
551
+ ## 🔌 Integration with Other Tools
552
+
553
+ ### PM2 Integration
211
554
 
212
555
  ```typescript
213
- const progressBar = new SmartlogProgressBar({
214
- total: 100, // Total number of items
215
- width: 40, // Width of the progress bar
216
- complete: '', // Character for completed section
217
- incomplete: '', // Character for incomplete section
218
- showEta: true, // Show estimated time remaining
219
- showPercent: true, // Show percentage
220
- showCount: true // Show count (e.g., "50/100")
221
- });
556
+ // ecosystem.config.js
557
+ module.exports = {
558
+ apps: [{
559
+ name: 'api',
560
+ script: './dist/index.js',
561
+ error_file: '/dev/null', // Disable PM2 error log
562
+ out_file: '/dev/null', // Disable PM2 out log
563
+ merge_logs: true,
564
+ env: {
565
+ NODE_ENV: 'production',
566
+ // smartlog handles all logging
567
+ }
568
+ }]
569
+ };
570
+ ```
222
571
 
223
- // Update progress
224
- progressBar.update(25); // Set to 25% progress
572
+ ### Docker Integration
225
573
 
226
- // Increment progress
227
- progressBar.increment(5); // Increase by 5 units
574
+ ```dockerfile
575
+ FROM node:18-alpine
576
+ WORKDIR /app
577
+ COPY . .
578
+ RUN pnpm install --production
228
579
 
229
- // Change color
230
- progressBar.setColor('blue');
580
+ # smartlog handles structured logging
581
+ # No need for special log drivers
582
+ CMD ["node", "dist/index.js"]
583
+ ```
231
584
 
232
- // Complete the progress bar
233
- progressBar.complete();
585
+ ```yaml
586
+ # docker-compose.yml
587
+ services:
588
+ app:
589
+ build: .
590
+ environment:
591
+ - NODE_ENV=production
592
+ # Logs are structured JSON, perfect for log aggregators
593
+ logging:
594
+ driver: "json-file"
595
+ options:
596
+ max-size: "10m"
597
+ max-file: "3"
234
598
  ```
235
599
 
236
- #### Non-Interactive Environments
600
+ ## 🏆 Best Practices
237
601
 
238
- Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output) and fallback to plain text logging:
602
+ ### 1. Use Semantic Log Levels
239
603
 
604
+ ```typescript
605
+ // ✅ Good - semantic and meaningful
606
+ logger.log('lifecycle', 'Server starting on port 3000');
607
+ logger.log('success', 'Database connection established');
608
+ logger.log('error', 'Failed to process payment', { orderId, error });
609
+
610
+ // ❌ Bad - everything is 'info'
611
+ logger.log('info', 'Server starting');
612
+ logger.log('info', 'Database connected');
613
+ logger.log('info', 'Error: payment failed');
240
614
  ```
241
- [Loading] Connecting to server
242
- [Success] Connected to server
243
- [Loading] Fetching records
244
- Progress: 50% (50/100)
245
- Progress: 100% (100/100)
246
- [Success] Fetching complete
615
+
616
+ ### 2. Include Structured Data
617
+
618
+ ```typescript
619
+ // Good - structured data for analysis
620
+ logger.log('error', 'API request failed', {
621
+ endpoint: '/api/users',
622
+ statusCode: 500,
623
+ duration: 1234,
624
+ userId: 'usr_123',
625
+ errorCode: 'INTERNAL_ERROR'
626
+ });
627
+
628
+ // ❌ Bad - data embedded in message
629
+ logger.log('error', `API request to /api/users failed with 500 in 1234ms for user usr_123`);
247
630
  ```
248
631
 
249
- ## Advanced Usage
632
+ ### 3. Use Log Groups for Correlation
250
633
 
251
- ### Capturing All Console Output
634
+ ```typescript
635
+ // ✅ Good - correlated logs
636
+ async function processOrder(orderId: string) {
637
+ const logGroup = logger.createLogGroup(orderId);
638
+
639
+ logGroup.log('info', 'Processing order');
640
+ logGroup.log('debug', 'Validating items');
641
+ logGroup.log('info', 'Charging payment');
642
+ logGroup.log('success', 'Order processed');
643
+ }
644
+
645
+ // ❌ Bad - no correlation
646
+ async function processOrder(orderId: string) {
647
+ logger.log('info', `Processing order ${orderId}`);
648
+ logger.log('debug', `Validating items for ${orderId}`);
649
+ logger.log('info', `Charging payment for ${orderId}`);
650
+ }
651
+ ```
252
652
 
253
- Capture all `console.log` and `console.error` output through Smartlog:
653
+ ### 4. Environment-Specific Configuration
254
654
 
255
655
  ```typescript
256
- logger.enableConsole({ captureAll: true });
656
+ // Good - different configs per environment
657
+ const logger = new Smartlog({
658
+ logContext: {
659
+ environment: process.env.NODE_ENV,
660
+ // ... other context
661
+ },
662
+ minimumLogLevel: process.env.NODE_ENV === 'production' ? 'info' : 'silly'
663
+ });
664
+
665
+ // Add destinations based on environment
666
+ if (process.env.NODE_ENV === 'production') {
667
+ logger.addLogDestination(clickhouseDestination);
668
+ logger.addLogDestination(alertingDestination);
669
+ } else {
670
+ logger.enableConsole();
671
+ }
257
672
  ```
258
673
 
259
- ### Increment Logging
674
+ ## 📖 API Reference
260
675
 
261
- For metrics and counters:
676
+ ### Smartlog Class
262
677
 
263
678
  ```typescript
264
- logger.increment('info', 'api_requests', { endpoint: '/users' });
679
+ class Smartlog {
680
+ constructor(options?: ISmartlogOptions)
681
+
682
+ // Logging methods
683
+ log(level: TLogLevel, message: string, data?: any, correlation?: ILogCorrelation): void
684
+ increment(level: TLogLevel, key: string, data?: any): void
685
+
686
+ // Configuration
687
+ enableConsole(options?: IConsoleOptions): void
688
+ addLogDestination(destination: ILogDestination): void
689
+ addLogContext(context: Partial<ILogContext>): void
690
+
691
+ // Log groups
692
+ createLogGroup(transactionId?: string): LogGroup
693
+ createScope(scopeName: string): Smartlog
694
+ }
265
695
  ```
266
696
 
267
- ### Log Correlation
697
+ ### Log Levels
268
698
 
269
- Correlate logs across services with correlation IDs:
699
+ ```typescript
700
+ type TLogLevel =
701
+ | 'silly' // Very verbose debugging
702
+ | 'debug' // Debug information
703
+ | 'info' // Informational messages
704
+ | 'note' // Notable events
705
+ | 'ok' // Success confirmation
706
+ | 'success' // Major success
707
+ | 'warn' // Warning messages
708
+ | 'error' // Error messages
709
+ | 'lifecycle' // Application lifecycle events
710
+ ```
711
+
712
+ ### Log Package Structure
270
713
 
271
714
  ```typescript
272
- logger.log('info', 'Request received', { userId: 'user-123' }, {
273
- id: 'req-abc-123',
274
- type: 'service',
275
- transaction: 'tx-payment-456'
276
- });
715
+ interface ILogPackage {
716
+ timestamp: number;
717
+ level: TLogLevel;
718
+ message: string;
719
+ data?: any;
720
+ context: ILogContext;
721
+ correlation?: ILogCorrelation;
722
+ }
277
723
  ```
278
724
 
279
- ## API Documentation
725
+ For complete API documentation, see [API.md](API.md).
726
+
727
+ ## 🤝 Contributing
280
728
 
281
- For detailed API documentation, see the [API.md](API.md) file.
729
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
282
730
 
283
- ## License and Legal Information
731
+ ## 📄 License and Legal Information
284
732
 
285
- This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
733
+ This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
286
734
 
287
735
  **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
288
736
 
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartlog',
6
- version: '3.1.8',
6
+ version: '3.1.9',
7
7
  description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.'
8
8
  }