@wgtechlabs/log-engine 2.2.0 → 2.2.1-patch.2a805ed

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 (3) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +941 -935
  3. package/package.json +130 -129
package/README.md CHANGED
@@ -1,935 +1,941 @@
1
- # Log Engine 📜🚂 [![made by](https://img.shields.io/badge/made%20by-WG%20Tech%20Labs-0060a0.svg?logo=github&longCache=true&labelColor=181717&style=flat-square)](https://github.com/wgtechlabs)
2
-
3
- [![codecov](https://img.shields.io/codecov/c/github/wgtechlabs/log-engine?token=PWRJTBVKQ9&style=flat-square&logo=codecov&labelColor=181717)](https://codecov.io/gh/wgtechlabs/log-engine) [![npm downloads](https://img.shields.io/npm/dm/%40wgtechlabs%2Flog-engine?style=flat-square&logo=npm&label=installs&labelColor=181717&color=%23CD0000)](https://www.npmjs.com/package/@wgtechlabs/log-engine) [![sponsors](https://img.shields.io/badge/sponsor-%E2%9D%A4-%23db61a2.svg?&logo=github&logoColor=white&labelColor=181717&style=flat-square)](https://github.com/sponsors/wgtechlabs) [![release](https://img.shields.io/github/release/wgtechlabs/log-engine.svg?logo=github&labelColor=181717&color=green&style=flat-square)](https://github.com/wgtechlabs/log-engine/releases) [![star](https://img.shields.io/github/stars/wgtechlabs/log-engine.svg?&logo=github&labelColor=181717&color=yellow&style=flat-square)](https://github.com/wgtechlabs/log-engine/stargazers) [![license](https://img.shields.io/github/license/wgtechlabs/log-engine.svg?&logo=github&labelColor=181717&style=flat-square)](https://github.com/wgtechlabs/log-engine/blob/main/license)
4
-
5
- [![banner](https://raw.githubusercontent.com/wgtechlabs/log-engine/main/.github/assets/repo_banner.jpg)](https://github.com/wgtechlabs/log-engine)
6
-
7
- WG's Log Engine is the **ultimate logging solution for Node.js developers** - a lightweight, battle-tested utility specifically engineered for Discord bots, Telegram bots, web servers, APIs, and server-side applications. Born from real-world development challenges and proven in production environments like the [Unthread Discord Bot](https://github.com/wgtechlabs/unthread-discord-bot/), Log Engine delivers enterprise-grade logging with zero complexity, beautiful color-coded console output, **revolutionary configurable output routing**, and **advanced automatic data redaction with comprehensive PII protection**.
8
-
9
- **The first logging library with built-in advanced PII protection, configurable output handlers, and comprehensive TypeScript support.** Stop wrestling with logging configurations and start building amazing applications safely. Whether you're creating the next viral Discord community bot, building high-performance APIs, developing microservices, or deploying production servers, Log Engine provides intelligent logging with vibrant colors, flexible output routing to any destination, advanced customizable redaction patterns, and automatic sensitive data protection that scales with your application's growth - from your first "Hello World" to handling millions of requests across distributed systems.
10
-
11
- ## âŖī¸ Motivation
12
-
13
- Picture this: It's 2 AM, your server is crashing in production, and you're staring at a terminal filled with thousands of debug messages mixed with critical errors. Sound familiar? I've been there too many times. I created Log Engine because every developer deserves to sleep peacefully, knowing their logs are working intelligently in the background.
14
-
15
- Log Engine transforms your development experience from chaotic debugging sessions into confident, data-driven problem solving. No more guessing what went wrong, no more drowning in irrelevant logs, no more manual configuration headaches. Just clear, contextual information exactly when and where you need it. Because great applications deserve great logging, and great developers deserve tools that just work.
16
-
17
- ## ✨ Key Features
18
-
19
- - **🔒 Advanced Data Redaction (Enhanced!)**: Built-in PII protection with **custom regex patterns**, **dynamic field management**, and **environment-based configuration** - the first logging library with comprehensive security-first logging by default.
20
- - **đŸŽ¯ Configurable Output Handlers (New!)**: Revolutionary output routing system supporting **custom destinations**, **multiple simultaneous outputs**, and **production-ready handlers** - redirect logs to files, HTTP endpoints, GUI applications, testing frameworks, or any custom destination with zero configuration complexity.
21
- - **⚡ Custom Redaction Patterns**: Add your own regex patterns for advanced field detection and enterprise-specific data protection requirements.
22
- - **đŸŽ¯ Dynamic Field Management**: Runtime configuration of sensitive fields with case-insensitive matching and partial field name detection.
23
- - **đŸ› ī¸ Developer-Friendly API**: Advanced redaction methods including `testFieldRedaction()`, `withoutRedaction()`, and comprehensive configuration management.
24
- - **📊 Comprehensive TypeScript Support**: Full type definitions with 15+ interfaces covering all functionality for maximum developer experience and IDE support.
25
- - **🚀 Lightweight & Fast**: Minimal overhead with maximum performance - designed to enhance your application, not slow it down.
26
- - **📚 No Learning Curve**: Dead simple API that you can master in seconds. No extensive documentation, complex configurations, or setup required - Log Engine works instantly.
27
- - **🌈 Colorized Console Output**: Beautiful ANSI color-coded log levels with intelligent terminal formatting - instantly identify message severity at a glance with color-coded output.
28
- - **đŸŽ›ī¸ Multiple Log Modes**: Support for DEBUG, INFO, WARN, ERROR, SILENT, OFF, and special LOG levels with smart filtering - just set your mode and let it handle the rest.
29
- - **âš™ī¸ Auto-Configuration**: Intelligent environment-based setup using NODE_ENV variables. No config files, initialization scripts, or manual setup - Log Engine works perfectly out of the box.
30
- - **✨ Enhanced Formatting**: Structured log entries with dual timestamps (ISO + human-readable) and colored level indicators for maximum readability.
31
- - **🔗 Zero Dependencies**: No external dependencies for maximum compatibility and security - keeps your bundle clean and your project simple.
32
- - **🔌 Easy Integration**: Simple API that works seamlessly with existing Node.js applications. Just `import` and start logging - no middleware, plugins, or configuration required.
33
-
34
- ## âš ī¸ Breaking Changes Notice
35
-
36
- **v3.0.0 Breaking Change**: The legacy `level` configuration will be removed in v3.0.0. If you're using `LogEngine.configure({ level: LogLevel.DEBUG })`, please migrate to `LogEngine.configure({ mode: LogMode.DEBUG })`. See our [Migration Guide](#migration-guide-loglevel--logmode) for details.
37
-
38
- ## 🤔 How It Works
39
- <!-- markdownlint-disable MD051 -->
40
- 1. Log Engine automatically detects your environment using `NODE_ENV` and sets appropriate log levels for optimal performance
41
- 2. When you call logging methods, messages are filtered based on the configured severity level (only messages at or above the set level are displayed)
42
- 3. Each log message is instantly formatted with precise timestamps in both ISO and human-readable formats
43
- 4. Messages are output to the console with **colorized level indicators and timestamps**, making debugging and monitoring effortless - errors show in red, warnings in yellow, info in blue, and debug in purple
44
- 5. ANSI color codes ensure compatibility across different terminal environments while maintaining beautiful, readable output
45
-
46
- Ready to streamline your application logging? Get started in seconds with our [simple installation](#đŸ“Ļ-installation)!
47
- <!-- markdownlint-enable MD051 -->
48
- ## 🤗 Special Thanks
49
-
50
- <!-- markdownlint-disable MD033 -->
51
- | <div align="center">💎 Platinum Sponsor</div> |
52
- |:-------------------------------------------:|
53
- | <a href="https://unthread.com"><img src="https://raw.githubusercontent.com/wgtechlabs/unthread-discord-bot/main/.github/assets/sponsors/platinum_unthread.png" width="250" alt="Unthread"></a> |
54
- | <div align="center"><a href="https://unthread.com" target="_blank"><b>Unthread</b></a><br/>Streamlined support ticketing for modern teams.</div> |
55
- <!-- markdownlint-enable MD033 -->
56
-
57
- ## 💸 Sponsored Ads
58
-
59
- Open source development is resource-intensive. These **sponsored ads help keep Log Engine free and actively maintained** while connecting you with tools and services that support open-source development.
60
-
61
- [![sponsored ads](https://gitads.dev/v1/ad-serve?source=wgtechlabs/log-engine@github)](https://gitads.dev/v1/ad-track?source=wgtechlabs/log-engine@github)
62
-
63
- ## đŸ“Ļ Installation
64
-
65
- Install the package using yarn (recommended):
66
-
67
- ```bash
68
- yarn add @wgtechlabs/log-engine
69
- ```
70
-
71
- Or using npm:
72
-
73
- ```bash
74
- npm install @wgtechlabs/log-engine
75
- ```
76
-
77
- > **Note**: This project uses yarn as the primary package manager for development. If you're contributing to the project, please use yarn to ensure consistency with the development environment.
78
-
79
- ## đŸ•šī¸ Usage
80
-
81
- > **âš ī¸ Important**: If you're using the legacy `level` configuration, please migrate to `mode`. The `level` configuration is deprecated and will be removed in v3.0.0. See the [Migration Guide](#migration-guide-loglevel--logmode) below.
82
-
83
- ### Quick Start
84
-
85
- ```typescript
86
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
87
-
88
- // Basic usage with auto-configuration based on NODE_ENV
89
- LogEngine.debug('This is a debug message');
90
- LogEngine.info('This is an info message');
91
- LogEngine.warn('This is a warning message');
92
- LogEngine.error('This is an error message');
93
- LogEngine.log('This is a critical message that always shows');
94
-
95
- // Advanced automatic data redaction (no configuration needed!)
96
- LogEngine.info('User login', {
97
- username: 'john_doe', // ✅ Visible
98
- password: 'secret123', // ❌ [REDACTED]
99
- email: 'john@example.com', // ❌ [REDACTED]
100
- apiKey: 'apikey123' // ❌ [REDACTED]
101
- });
102
-
103
- // Advanced redaction features - Add custom patterns
104
- LogEngine.addCustomRedactionPatterns([/internal.*/i, /company.*/i]);
105
- LogEngine.addSensitiveFields(['companySecret', 'internalToken']);
106
-
107
- // Test field redaction
108
- console.log(LogEngine.testFieldRedaction('password')); // true
109
- console.log(LogEngine.testFieldRedaction('username')); // false
110
-
111
- // Raw logging for debugging (bypasses redaction)
112
- LogEngine.withoutRedaction().info('Debug data', { password: 'visible-in-debug' });
113
-
114
- // NEW: Custom output destinations (v2.0+)
115
- LogEngine.configure({
116
- outputHandler: (level, message, data) => {
117
- // Send logs anywhere: GUI apps, files, APIs, databases
118
- myCustomHandler(level, message, data);
119
- },
120
- suppressConsoleOutput: true // Optional: disable console
121
- });
122
-
123
- // NEW: Multiple outputs simultaneously
124
- LogEngine.configure({
125
- outputs: [
126
- 'console', // Built-in console
127
- myFileHandler, // Custom file handler
128
- myMonitoringHandler // Custom monitoring
129
- ]
130
- });
131
- ```
132
-
133
- ### Mode-Based Configuration (Recommended)
134
-
135
- Log Engine now uses a modern **LogMode** system that separates message severity from output control:
136
-
137
- ```typescript
138
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
139
-
140
- // Configure using LogMode (recommended approach)
141
- LogEngine.configure({ mode: LogMode.DEBUG }); // Most verbose
142
- LogEngine.configure({ mode: LogMode.INFO }); // Balanced
143
- LogEngine.configure({ mode: LogMode.WARN }); // Focused
144
- LogEngine.configure({ mode: LogMode.ERROR }); // Minimal
145
- LogEngine.configure({ mode: LogMode.SILENT }); // Critical only
146
- LogEngine.configure({ mode: LogMode.OFF }); // Complete silence
147
-
148
- // Environment-based configuration example
149
- const env = process.env.NODE_ENV || 'development';
150
-
151
- if (env === 'production') {
152
- LogEngine.configure({ mode: LogMode.INFO });
153
- } else if (env === 'staging') {
154
- LogEngine.configure({ mode: LogMode.WARN });
155
- } else {
156
- LogEngine.configure({ mode: LogMode.DEBUG });
157
- }
158
-
159
- // Now use Log Engine - only messages appropriate for the mode will be shown
160
- LogEngine.debug('This will only show in DEBUG mode');
161
- LogEngine.info('General information');
162
- LogEngine.warn('Warning message');
163
- LogEngine.error('Error message');
164
- LogEngine.log('Critical message that always shows');
165
- ```
166
-
167
- ### Legacy Level-Based Configuration (âš ī¸ Deprecated)
168
-
169
- **âš ī¸ DEPRECATION WARNING**: The `level` configuration is deprecated and will be removed in **v3.0.0**. Please use `mode` instead.
170
-
171
- For backwards compatibility, the old `LogLevel` API is still supported but shows deprecation warnings:
172
-
173
- ```typescript
174
- import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
175
-
176
- // âš ī¸ DEPRECATED: Legacy configuration (shows warning, will be removed in v3.0.0)
177
- LogEngine.configure({ level: LogLevel.DEBUG }); // Triggers deprecation warning
178
- LogEngine.configure({ level: LogLevel.INFO }); // Triggers deprecation warning
179
- LogEngine.configure({ level: LogLevel.WARN }); // Triggers deprecation warning
180
- LogEngine.configure({ level: LogLevel.ERROR }); // Triggers deprecation warning
181
-
182
- // ✅ RECOMMENDED: Use the modern LogMode API instead
183
- LogEngine.configure({ mode: LogMode.DEBUG }); // No warnings, future-proof
184
- ```
185
-
186
- **Why migrate to LogMode?**
187
-
188
- - No deprecation warnings
189
- - Future-proof API that won't be removed
190
- - Better separation of concerns
191
- - Access to all v2.0+ features including output handlers
192
- - Clearer, more intuitive configuration
193
-
194
- ### Migration Guide: LogLevel → LogMode
195
-
196
- **âš ī¸ IMPORTANT DEPRECATION NOTICE**: The `level` configuration is **deprecated as of v2.0.0** and will be **removed in v3.0.0**. Please migrate to the new `mode` configuration.
197
-
198
- **Version 1.2.0+** introduces the new LogMode system for better separation of concerns. Here's how to migrate:
199
-
200
- ```typescript
201
- // ❌ OLD (v1.1.0 and earlier) - DEPRECATED, will be removed in v3.0.0
202
- import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
203
- LogEngine.configure({ level: LogLevel.DEBUG }); // Shows deprecation warning
204
-
205
- // ✅ NEW (v2.0.0+) - recommended approach with advanced features
206
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
207
- LogEngine.configure({ mode: LogMode.DEBUG }); // Modern, future-proof API
208
- ```
209
-
210
- **Migration Benefits:**
211
-
212
- **Key Benefits of LogMode:**
213
-
214
- - **Clearer API**: Separates message severity (`LogLevel`) from output control (`LogMode`)
215
- - **Better Environment Defaults**: `development→DEBUG`, `staging→WARN`, `test→ERROR`
216
- - **Advanced Features**: New redaction APIs and TypeScript interfaces work with LogMode
217
- - **Future-Proof**: All new features use the LogMode system
218
- - **100% Backwards Compatible**: Existing code continues to work unchanged (with deprecation warnings)
219
- - **No Breaking Changes in v2.0**: Legacy `level` support maintained until v3.0.0
220
-
221
- ### Color-Coded Output 🎨
222
-
223
- Log Engine now features beautiful, color-coded console output that makes debugging and monitoring a breeze:
224
-
225
- ```typescript
226
- import { LogEngine } from '@wgtechlabs/log-engine';
227
-
228
- // Each log level gets its own distinct color for instant recognition
229
- LogEngine.debug('🔍 Debugging user authentication flow'); // Purple/Magenta
230
- LogEngine.info('â„šī¸ User successfully logged in'); // Blue
231
- LogEngine.warn('âš ī¸ API rate limit at 80% capacity'); // Yellow
232
- LogEngine.error('❌ Database connection timeout'); // Red
233
- LogEngine.log('🚀 Application started successfully'); // Green
234
- ```
235
-
236
- **Why Colors Matter:**
237
-
238
- - **Instant Recognition**: Quickly spot errors, warnings, and debug info without reading every line
239
- - **Better Debugging**: Visually separate different types of messages during development
240
- - **Production Monitoring**: Easily scan logs for critical issues in terminal environments
241
- - **Enhanced Readability**: Color-coded timestamps and level indicators reduce eye strain
242
-
243
- ### Log Modes
244
-
245
- Log Engine uses a **LogMode** system that controls output verbosity and filtering:
246
-
247
- - `LogMode.DEBUG` (0) - Most verbose: shows DEBUG, INFO, WARN, ERROR, LOG messages
248
- - `LogMode.INFO` (1) - Balanced: shows INFO, WARN, ERROR, LOG messages
249
- - `LogMode.WARN` (2) - Focused: shows WARN, ERROR, LOG messages
250
- - `LogMode.ERROR` (3) - Minimal: shows ERROR, LOG messages
251
- - `LogMode.SILENT` (4) - Critical only: shows LOG messages only
252
- - `LogMode.OFF` (5) - Complete silence: shows no messages at all
253
-
254
- ### Message Severity Levels
255
-
256
- Individual log messages have severity levels that determine their importance:
257
-
258
- - `LogLevel.DEBUG` (0) - Detailed information for debugging
259
- - `LogLevel.INFO` (1) - General information
260
- - `LogLevel.WARN` (2) - Warning messages
261
- - `LogLevel.ERROR` (3) - Error messages
262
- - `LogLevel.LOG` (99) - Critical messages that always show (except when OFF mode is set)
263
-
264
- ### Auto-Configuration
265
-
266
- Log Engine automatically configures itself based on the `NODE_ENV` environment variable:
267
-
268
- - `development` → `LogMode.DEBUG` (most verbose)
269
- - `production` → `LogMode.INFO` (balanced)
270
- - `staging` → `LogMode.WARN` (focused)
271
- - `test` → `LogMode.ERROR` (minimal)
272
- - `default` → `LogMode.INFO` (balanced)
273
-
274
- ### Special LOG Level
275
-
276
- The `LOG` level is special and behaves differently from other levels:
277
-
278
- - **Always Visible**: LOG messages are always displayed regardless of the configured log mode (except when OFF mode is set)
279
- - **Critical Information**: Perfect for essential system messages, application lifecycle events, and operational information that must never be filtered out
280
- - **Green Color**: Uses green coloring to distinguish it from other levels
281
- - **Use Cases**: Application startup/shutdown, server listening notifications, critical configuration changes, deployment information
282
-
283
- ```typescript
284
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
285
-
286
- // Even with SILENT mode, LOG messages still appear
287
- LogEngine.configure({ mode: LogMode.SILENT });
288
-
289
- LogEngine.debug('Debug message'); // Hidden
290
- LogEngine.info('Info message'); // Hidden
291
- LogEngine.warn('Warning message'); // Hidden
292
- LogEngine.error('Error message'); // Hidden
293
- LogEngine.log('Server started on port 3000'); // ✅ Always visible!
294
-
295
- // But with OFF mode, even LOG messages are hidden
296
- LogEngine.configure({ mode: LogMode.OFF });
297
- LogEngine.log('This LOG message is hidden'); // ❌ Hidden with OFF mode
298
- ```
299
-
300
- ### Complete Silence with OFF Mode
301
-
302
- The `OFF` mode provides complete logging silence when you need to disable all output:
303
-
304
- - **Total Silence**: Disables ALL logging including the special LOG level messages
305
- - **Testing & CI/CD**: Perfect for automated testing environments where no console output is desired
306
- - **Performance**: Minimal overhead when logging is completely disabled
307
- - **Use Cases**: Unit tests, CI/CD pipelines, production environments requiring zero log output
308
-
309
- ```typescript
310
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
311
-
312
- // Comparison: SILENT vs OFF
313
- LogEngine.configure({ mode: LogMode.SILENT });
314
- LogEngine.info('Info message'); // Hidden
315
- LogEngine.log('Critical message'); // ✅ Still visible with SILENT
316
-
317
- LogEngine.configure({ mode: LogMode.OFF });
318
- LogEngine.info('Info message'); // Hidden
319
- LogEngine.log('Critical message'); // ❌ Hidden with OFF - complete silence!
320
- ```
321
-
322
- ### Log Format
323
-
324
- Log messages are beautifully formatted with colorized timestamps, levels, and smart terminal output:
325
-
326
- ```bash
327
- # Example colorized output (colors visible in terminal)
328
- [2025-05-29T16:57:45.678Z][4:57PM][DEBUG]: Debugging application flow
329
- [2025-05-29T16:57:46.123Z][4:57PM][INFO]: Server started successfully
330
- [2025-05-29T16:57:47.456Z][4:57PM][WARN]: API rate limit approaching
331
- [2025-05-29T16:57:48.789Z][4:57PM][ERROR]: Database connection failed
332
- [2025-05-29T16:57:49.012Z][4:57PM][LOG]: Application startup complete
333
- ```
334
-
335
- **Color Scheme:**
336
-
337
- - đŸŸŖ **DEBUG**: Magenta/Purple - Detailed debugging information
338
- - đŸ”ĩ **INFO**: Blue - General informational messages
339
- - 🟡 **WARN**: Yellow - Warning messages that need attention
340
- - 🔴 **ERROR**: Red - Error messages requiring immediate action
341
- - đŸŸĸ **LOG**: Green - Critical messages that always display
342
- - âšĢ **Timestamps**: Gray (ISO) and Cyan (local time) for easy scanning
343
-
344
- ### Customizing Log Elements
345
-
346
- **LogEngine v2.1+ introduces the ability to customize which elements are included in your log output** while keeping log levels mandatory for clarity and consistency.
347
-
348
- #### Available Customization Options
349
-
350
- You can control the inclusion of timestamp elements:
351
-
352
- - **ISO Timestamp**: `[2025-05-29T16:57:45.678Z]` - Precise UTC timestamp
353
- - **Local Time**: `[4:57PM]` - Human-readable local time
354
- - **Log Level**: `[INFO]` - Always included (non-customizable as per design)
355
-
356
- #### Format Configuration Examples
357
-
358
- ```typescript
359
- import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
360
-
361
- // Default format (backward compatible)
362
- LogEngine.configure({ mode: LogMode.DEBUG });
363
- LogEngine.info('Server started');
364
- // Output: [2025-05-29T16:57:45.678Z][4:57PM][INFO]: Server started
365
-
366
- // Only ISO timestamp
367
- LogEngine.configure({
368
- mode: LogMode.DEBUG,
369
- format: {
370
- includeIsoTimestamp: true,
371
- includeLocalTime: false
372
- }
373
- });
374
- LogEngine.info('Database connected');
375
- // Output: [2025-05-29T16:57:45.678Z][INFO]: Database connected
376
-
377
- // Only local time
378
- LogEngine.configure({
379
- mode: LogMode.DEBUG,
380
- format: {
381
- includeIsoTimestamp: false,
382
- includeLocalTime: true
383
- }
384
- });
385
- LogEngine.warn('Rate limit approaching');
386
- // Output: [4:57PM][WARN]: Rate limit approaching
387
-
388
- // Minimal format (no timestamps)
389
- LogEngine.configure({
390
- mode: LogMode.DEBUG,
391
- format: {
392
- includeIsoTimestamp: false,
393
- includeLocalTime: false
394
- }
395
- });
396
- LogEngine.error('Connection failed');
397
- // Output: [ERROR]: Connection failed
398
- ```
399
-
400
- #### Benefits of Log Element Customization
401
-
402
- - **đŸŽ¯ Reduced Verbosity**: Remove unnecessary timestamp information in containerized environments where external logging systems add timestamps
403
- - **📱 Space Efficiency**: Minimize log line length for mobile or constrained display environments
404
- - **🔧 Integration Ready**: Match existing log format requirements in your infrastructure
405
- - **⚡ Performance**: Slightly reduced formatting overhead when timestamps are disabled
406
- - **🔒 Backward Compatible**: Default behavior remains unchanged - existing code continues to work without modifications
407
-
408
- **Note**: Log levels (`[DEBUG]`, `[INFO]`, `[WARN]`, `[ERROR]`, `[LOG]`) are always included regardless of configuration to maintain log clarity and filtering capabilities.
409
-
410
- ## 🔒 Advanced Data Redaction
411
-
412
- **LogEngine features comprehensive built-in PII protection with advanced customization capabilities that automatically redacts sensitive information from your logs.** This security-first approach prevents accidental exposure of passwords, tokens, emails, and other sensitive data while maintaining full debugging capabilities with enterprise-grade flexibility.
413
-
414
- ### Zero Configuration Security
415
-
416
- Just use LogEngine normally - **sensitive data is automatically protected**:
417
-
418
- ```typescript
419
- import { LogEngine } from '@wgtechlabs/log-engine';
420
-
421
- // ✅ Automatic redaction - no setup needed!
422
- LogEngine.info('User authentication', {
423
- username: 'john_doe', // ✅ Visible
424
- password: 'secret123', // ❌ [REDACTED]
425
- email: 'john@example.com', // ❌ [REDACTED]
426
- apiKey: 'apikey123', // ❌ [REDACTED]
427
- timestamp: new Date() // ✅ Visible
428
- });
429
-
430
- // Output: [INFO]: User authentication {"username":"john_doe","password":"[REDACTED]","email":"[REDACTED]","apiKey":"[REDACTED]","timestamp":"2025-06-17T..."}
431
- ```
432
-
433
- ### Protected Data Types
434
-
435
- **50+ sensitive patterns automatically detected:**
436
-
437
- - **Authentication**: `password`, `token`, `apiKey`, `secret`, `jwt`, `auth`, `sessionId`
438
- - **Personal Info**: `email`, `phone`, `ssn`, `firstName`, `lastName`, `address`
439
- - **Financial**: `creditCard`, `cvv`, `bankAccount`, `routingNumber`
440
- - **System**: `clientSecret`, `privateKey`, `webhookSecret`
441
-
442
- ### Deep Object Scanning
443
-
444
- Automatically scans nested objects and arrays:
445
-
446
- ```typescript
447
- LogEngine.warn('Payment processing', {
448
- order: {
449
- id: 'order-123', // ✅ Visible
450
- customer: {
451
- username: 'customer1', // ✅ Visible
452
- email: 'user@example.com', // ❌ [REDACTED]
453
- creditCard: '4532-****' // ❌ [REDACTED]
454
- }
455
- },
456
- metadata: {
457
- processor: 'stripe',
458
- apiSecret: 'sk_live_...' // ❌ [REDACTED]
459
- }
460
- });
461
- ```
462
-
463
- ### Content Truncation
464
-
465
- Large content fields are automatically truncated to prevent log bloat:
466
-
467
- ```typescript
468
- LogEngine.debug('Large payload', {
469
- content: 'Very long content...'.repeat(100), // Truncated at 100 chars + "... [TRUNCATED]"
470
- size: 'large',
471
- processed: true
472
- });
473
- ```
474
-
475
- ### Development-Friendly Features
476
-
477
- **Raw Methods for Debugging:**
478
-
479
- ```typescript
480
- // âš ī¸ Use with caution - bypasses redaction
481
- LogEngine.debugRaw('Full debug data', {
482
- password: 'secret123', // âš ī¸ Visible (not redacted)
483
- apiKey: 'full-key' // âš ī¸ Visible (not redacted)
484
- });
485
-
486
- // Or use the helper method
487
- LogEngine.withoutRedaction().info('Debug mode', sensitiveData);
488
- ```
489
-
490
- **Environment-Based Control:**
491
-
492
- ```bash
493
- # Development - show everything (redaction disabled)
494
- NODE_ENV=development
495
-
496
- # Explicitly disable redaction
497
- LOG_REDACTION_DISABLED=true
498
- DEBUG_FULL_PAYLOADS=true
499
-
500
- # Custom redaction configuration
501
- LOG_REDACTION_TEXT="***CONFIDENTIAL***"
502
- LOG_MAX_CONTENT_LENGTH=200
503
- LOG_SENSITIVE_FIELDS="customField,companySecret,internalData"
504
- LOG_TRUNCATION_TEXT="... [CUSTOM_TRUNCATED]"
505
-
506
- # Advanced environment integration
507
- LOG_REDACTION_ENABLED=false # Alternative disable method
508
- ```
509
-
510
- ### Custom Configuration
511
-
512
- **Modify redaction behavior:**
513
-
514
- ```typescript
515
- // Custom redaction settings
516
- LogEngine.configureRedaction({
517
- redactionText: '***HIDDEN***',
518
- maxContentLength: 200,
519
- sensitiveFields: ['myCustomField', 'internalSecret']
520
- });
521
-
522
- // Get current configuration
523
- const config = LogEngine.getRedactionConfig();
524
- console.log(config);
525
- ```
526
-
527
- ### Advanced Redaction Features (v1.2.1+)
528
-
529
- **Custom Patterns & Dynamic Field Management:**
530
-
531
- ```typescript
532
- // Add custom regex patterns for enterprise-specific data protection
533
- LogEngine.addCustomRedactionPatterns([
534
- /internal.*/i, // Matches any field starting with "internal"
535
- /company.*/i, // Matches any field starting with "company"
536
- /^config[A-Z]/ // Matches camelCase config fields
537
- ]);
538
-
539
- // Add custom sensitive field names dynamically
540
- LogEngine.addSensitiveFields(['companySecret', 'internalToken', 'proprietaryData']);
541
-
542
- // Test field redaction before logging
543
- if (LogEngine.testFieldRedaction('myField')) {
544
- console.log('Field will be redacted');
545
- }
546
-
547
- // Advanced configuration management
548
- LogEngine.configureRedaction({
549
- redactionText: '***CONFIDENTIAL***',
550
- maxContentLength: 150,
551
- customPatterns: [/private.*/i, /secret.*/i]
552
- });
553
-
554
- // Configuration utilities
555
- const currentConfig = LogEngine.getRedactionConfig();
556
- LogEngine.refreshRedactionConfig(); // Refresh from environment
557
- LogEngine.resetRedactionConfig(); // Reset to defaults
558
- LogEngine.clearCustomRedactionPatterns(); // Clear custom patterns
559
- ```
560
-
561
- **Enhanced Development Workflow:**
562
-
563
- ```typescript
564
- // Raw logging methods (bypass redaction) - use with caution
565
- LogEngine.debugRaw('Full debug data', { password: 'visible', apiKey: 'full-key' });
566
-
567
- // Temporary redaction bypass using helper method
568
- LogEngine.withoutRedaction().info('Debug mode', sensitiveData);
569
-
570
- // Compare outputs during development
571
- LogEngine.info('With redaction', data); // ❌ [REDACTED]
572
- LogEngine.withoutRedaction().info('Without redaction', data); // âš ī¸ Visible
573
- ```
574
-
575
- ### Environment Behavior
576
-
577
- | Environment | Redaction Status | Use Case |
578
- |-------------|------------------|----------|
579
- | **Production** | 🔒 **Active** | Full protection for live systems |
580
- | **Development** | đŸ› ī¸ **Disabled** | Full data visibility for debugging |
581
- | **Staging** | 🔒 **Active** | Test with production-like security |
582
- | **Test** | 🔒 **Active** | Consistent test environment |
583
-
584
- ### Security Benefits
585
-
586
- ✅ **Advanced Pattern Recognition** - Custom regex patterns for enterprise-specific data protection
587
- ✅ **Dynamic Field Management** - Runtime configuration of sensitive fields with intelligent matching
588
- ✅ **Comprehensive Testing API** - `testFieldRedaction()` for validation and debugging
589
- ✅ **Environment Integration** - Seamless configuration via environment variables
590
- ✅ **Development Workflow** - Raw logging methods and temporary redaction bypass for debugging
591
- ✅ **Prevents Data Leaks** - Automatic protection against accidental exposure with 50+ built-in patterns
592
- ✅ **Compliance Ready** - Helps meet GDPR, HIPAA, and other privacy requirements
593
- ✅ **Zero Configuration** - Secure by default, advanced features when needed
594
- ✅ **Performance Optimized** - Minimal overhead with intelligent processing and depth limiting
595
- ✅ **TypeScript Excellence** - Full type safety with comprehensive interfaces and type definitions
596
-
597
- **Perfect for:** Enterprise applications, compliance requirements, team development environments, production systems requiring both security and debugging flexibility, and any scenario where sensitive data protection is critical.
598
-
599
- ## đŸŽ¯ Configurable Output Handlers
600
-
601
- **LogEngine v2.0+ introduces revolutionary output routing capabilities that transform how and where your logs are delivered.** This powerful system enables custom log destinations, multiple simultaneous outputs, and production-ready handlers while maintaining the same simple API you know and love.
602
-
603
- ### Zero-Configuration Custom Routing
604
-
605
- **Redirect logs anywhere with a single configuration:**
606
-
607
- ```typescript
608
- import { LogEngine } from '@wgtechlabs/log-engine';
609
-
610
- // Redirect to GUI application
611
- LogEngine.configure({
612
- outputHandler: (level, message, data) => {
613
- updateReactUI({ level, message, timestamp: new Date() });
614
- },
615
- suppressConsoleOutput: true // Optional: disable console output
616
- });
617
-
618
- // Testing framework integration
619
- const capturedLogs = [];
620
- LogEngine.configure({
621
- outputHandler: (level, message, data) => {
622
- capturedLogs.push({ level, message, data });
623
- },
624
- suppressConsoleOutput: true
625
- });
626
-
627
- // Now use LogEngine normally - output goes to your custom handler
628
- LogEngine.info('User logged in', { userId: 123 });
629
- ```
630
-
631
- ### Multiple Simultaneous Outputs
632
-
633
- **Log to multiple destinations at once with built-in handlers:**
634
-
635
- ```typescript
636
- LogEngine.configure({
637
- outputs: [
638
- 'console', // Built-in console handler
639
- 'silent', // Built-in silent handler (no output)
640
- (level, message, data) => {
641
- // Custom file handler
642
- fs.appendFileSync('./app.log', `${new Date().toISOString()} [${level}] ${message}\n`);
643
- },
644
- (level, message, data) => {
645
- // Custom network handler
646
- if (level === 'error') {
647
- sendToMonitoringService({ level, message, data });
648
- }
649
- }
650
- ]
651
- });
652
-
653
- // Single log call outputs to all configured destinations
654
- LogEngine.error('Database connection failed', { retries: 3 });
655
- ```
656
-
657
- ### Production-Ready Advanced Handlers
658
-
659
- **Enterprise-grade file and HTTP outputs with advanced features:**
660
-
661
- ```typescript
662
- LogEngine.configure({
663
- enhancedOutputs: [
664
- 'console',
665
- {
666
- type: 'file',
667
- config: {
668
- filePath: './logs/app.log',
669
- maxFileSize: 10485760, // 10MB rotation
670
- maxBackupFiles: 5, // Keep 5 backup files
671
- append: true, // Append mode
672
- formatter: (level, message, data) => {
673
- const timestamp = new Date().toISOString();
674
- const dataStr = data ? ` | ${JSON.stringify(data)}` : '';
675
- return `[${timestamp}] ${level.toUpperCase()}: ${message}${dataStr}\n`;
676
- }
677
- }
678
- },
679
- {
680
- type: 'http',
681
- config: {
682
- url: 'https://api.datadog.com/v1/logs',
683
- method: 'POST',
684
- batchSize: 10, // Batch requests for performance
685
- timeout: 5000, // 5-second timeout
686
- headers: {
687
- 'Authorization': 'Bearer your-api-key',
688
- 'Content-Type': 'application/json'
689
- },
690
- formatter: (logs) => ({
691
- service: 'my-app',
692
- environment: process.env.NODE_ENV,
693
- logs: logs.map(log => ({
694
- timestamp: log.timestamp,
695
- level: log.level,
696
- message: log.message,
697
- metadata: log.data
698
- }))
699
- })
700
- }
701
- }
702
- ]
703
- });
704
- ```
705
-
706
- ### Configuration Priority System
707
-
708
- **Flexible configuration with intelligent priority handling:**
709
-
710
- ```typescript
711
- // Priority: outputs > enhancedOutputs > outputHandler > default console
712
-
713
- // Single handler (legacy compatibility)
714
- LogEngine.configure({
715
- outputHandler: myHandler,
716
- suppressConsoleOutput: true
717
- });
718
-
719
- // Multiple basic outputs - takes priority over outputHandler
720
- LogEngine.configure({
721
- outputs: ['console', myFileHandler, myNetworkHandler]
722
- });
723
-
724
- // Advanced outputs - used when outputs not specified
725
- LogEngine.configure({
726
- enhancedOutputs: [
727
- 'console',
728
- { type: 'file', config: { filePath: './app.log' } }
729
- ]
730
- });
731
- ```
732
-
733
- ### Error Handling & Resilience
734
-
735
- **Robust error handling ensures logging never breaks your application:**
736
-
737
- ```typescript
738
- LogEngine.configure({
739
- outputs: [
740
- 'console', // Always works
741
- (level, message) => {
742
- throw new Error('Handler failed'); // This failure won't break other outputs
743
- },
744
- (level, message) => {
745
- fs.writeFileSync('./logs/app.log', message); // This still works
746
- }
747
- ]
748
- });
749
-
750
- // If any handler fails, others continue working + fallback to console
751
- LogEngine.error('Critical error'); // Logs to console + working file handler
752
- ```
753
-
754
- ### Output Handler Benefits
755
-
756
- ✅ **GUI Integration** - Perfect for desktop applications, web dashboards, and real-time monitoring
757
- ✅ **Testing Support** - Capture and assert on log output in automated tests
758
- ✅ **Production Monitoring** - Send logs to Datadog, New Relic, CloudWatch, or custom endpoints
759
- ✅ **File Logging** - Persistent logs with automatic rotation and backup management
760
- ✅ **Silent Operation** - Disable console output for clean CLI tools and background services
761
- ✅ **Multi-Destination** - Log to console + file + network simultaneously with zero overhead
762
- ✅ **Error Isolation** - Failed outputs don't break other outputs or your application
763
- ✅ **Backward Compatible** - Existing code works unchanged, new features are opt-in only
764
- ✅ **TypeScript Ready** - Full type safety with comprehensive interfaces and IntelliSense
765
- ✅ **Zero Dependencies** - Built-in handlers use only Node.js standard library
766
-
767
- **Use Cases:** Desktop applications, testing frameworks, production monitoring, CI/CD pipelines, microservices, IoT devices, and any scenario requiring flexible log routing with enterprise-grade reliability.
768
-
769
- ## 📚 Comprehensive TypeScript Support
770
-
771
- **LogEngine v2.0+ includes extensive TypeScript definitions with 15+ interfaces for maximum type safety and developer experience:**
772
-
773
- ### Core Interfaces
774
-
775
- ```typescript
776
- import {
777
- LogEngine,
778
- LogMode,
779
- LogLevel,
780
- ILogEngine,
781
- ILogEngineWithoutRedaction,
782
- RedactionConfig,
783
- LoggerConfig,
784
- LogOutputHandler,
785
- FileOutputConfig,
786
- HttpOutputConfig,
787
- IDataRedactor
788
- } from '@wgtechlabs/log-engine';
789
-
790
- // Full type safety for all methods
791
- const config: RedactionConfig = {
792
- enabled: true,
793
- sensitiveFields: ['password', 'token'],
794
- redactionText: '[HIDDEN]',
795
- maxContentLength: 100,
796
- // ... fully typed configuration
797
- };
798
-
799
- // Type-safe output handler configuration
800
- const outputHandler: LogOutputHandler = (level, message, data) => {
801
- console.log(`[${level}] ${message}`, data);
802
- };
803
-
804
- const fileConfig: FileOutputConfig = {
805
- filePath: './app.log',
806
- maxFileSize: 1048576,
807
- maxBackupFiles: 3,
808
- formatter: (level, message, data) => `${level}: ${message}\n`
809
- };
810
-
811
- // Advanced redaction testing with return types
812
- const isRedacted: boolean = LogEngine.testFieldRedaction('password');
813
- const currentConfig: RedactionConfig = LogEngine.getRedactionConfig();
814
-
815
- // Type-safe raw logging
816
- const rawLogger: ILogEngineWithoutRedaction = LogEngine.withoutRedaction();
817
- rawLogger.info('Debug info', sensitiveData); // Fully typed methods
818
-
819
- // âš ī¸ Legacy (deprecated) - will be removed in v3.0.0
820
- import { LogLevel } from '@wgtechlabs/log-engine';
821
- LogEngine.configure({ level: LogLevel.DEBUG }); // Shows deprecation warning
822
- ```
823
-
824
- ### Available Interfaces
825
-
826
- - **`ILogEngine`** - Complete LogEngine API with all methods
827
- - **`ILogEngineWithoutRedaction`** - Raw logging methods interface
828
- - **`IDataRedactor`** - Static DataRedactor class methods
829
- - **`LogOutputHandler`** - Custom output handler function interface
830
- - **`FileOutputConfig`** - File output handler configuration
831
- - **`HttpOutputConfig`** - HTTP output handler configuration
832
- - **`RedactionConfig`** - Comprehensive redaction configuration
833
- - **`LoggerConfig`** - Logger configuration options (including output handlers)
834
- - **`LogEntry`** - Structured log entry interface
835
- - **`LogLevel`** - âš ī¸ **Deprecated**: Legacy level enumeration (use `LogMode` instead)
836
- - **`LogMode`** - ✅ **Recommended**: Modern mode enumeration
837
- - **`EnvironmentConfig`** - Environment variable documentation
838
- - **`EnvironmentConfig`** - Environment variable documentation
839
- - **Plus 5+ additional interfaces** for advanced output handling and configuration
840
-
841
- **IDE Benefits:** IntelliSense, auto-completion, parameter hints, error detection, and comprehensive documentation tooltips throughout your development workflow.
842
-
843
- ## đŸ’Ŧ Community Discussions
844
-
845
- Join our community discussions to get help, share ideas, and connect with other users:
846
-
847
- - đŸ“Ŗ **[Announcements](https://github.com/wgtechlabs/log-engine/discussions/categories/announcements)**: Official updates from the maintainer
848
- - 📸 **[Showcase](https://github.com/wgtechlabs/log-engine/discussions/categories/showcase)**: Show and tell your implementation
849
- - 💖 **[Wall of Love](https://github.com/wgtechlabs/log-engine/discussions/categories/wall-of-love)**: Share your experience with the library
850
- - 🛟 **[Help & Support](https://github.com/wgtechlabs/log-engine/discussions/categories/help-support)**: Get assistance from the community
851
- - 🧠 **[Ideas](https://github.com/wgtechlabs/log-engine/discussions/categories/ideas)**: Suggest new features and improvements
852
-
853
- ## 🛟 Help & Support
854
-
855
- ### Getting Help
856
-
857
- Need assistance with the library? Here's how to get help:
858
- <!-- markdownlint-disable MD051 -->
859
- - **Community Support**: Check the [Help & Support](https://github.com/wgtechlabs/log-engine/discussions/categories/help-support) category in our GitHub Discussions for answers to common questions.
860
- - **Ask a Question**: Create a [new discussion](https://github.com/wgtechlabs/log-engine/discussions/new?category=help-support) if you can't find answers to your specific issue.
861
- - **Documentation**: Review the [usage instructions](#đŸ•šī¸-usage) in this README for common examples and configurations.
862
- - **Known Issues**: Browse [existing issues](https://github.com/wgtechlabs/log-engine/issues) to see if your problem has already been reported.
863
- <!-- markdownlint-enable MD051 -->
864
-
865
- ### Reporting Issues
866
-
867
- Please report any issues, bugs, or improvement suggestions by [creating a new issue](https://github.com/wgtechlabs/log-engine/issues/new/choose). Before submitting, please check if a similar issue already exists to avoid duplicates.
868
-
869
- ### Security Vulnerabilities
870
-
871
- For security vulnerabilities, please do not report them publicly. Follow the guidelines in our [security policy](./security.md) to responsibly disclose security issues.
872
-
873
- Your contributions to improving this project are greatly appreciated! 🙏✨
874
-
875
- ## đŸŽ¯ Contributing
876
-
877
- Contributions are welcome, create a pull request to this repo and I will review your code. Please consider to submit your pull request to the `dev` branch. Thank you!
878
-
879
- **Development Environment:**
880
-
881
- - This project is configured for **local development workflows only** - no CI/CD setup required
882
- - Uses **yarn** as the primary package manager for consistency
883
- - Simple, cross-platform development setup with TypeScript, Jest, and ESLint
884
- - Clean test output maintained using `jest.setup.js` to suppress console noise during testing
885
- - All error logging functionality remains intact in production code
886
- - Security scanning available via Snyk for dependency vulnerability checking
887
-
888
- **Available Scripts:**
889
-
890
- - `yarn test` - Run all tests
891
- - `yarn test:watch` - Run tests in watch mode
892
- - `yarn test:coverage` - Run tests with coverage reporting
893
- - `yarn lint` - Run TypeScript and code quality checks
894
- - `yarn lint:fix` - Automatically fix linting issues
895
- - `yarn lint:security` - Run security-focused linting
896
- - `yarn secure` - Run comprehensive security checks
897
- - `yarn build` - Build the TypeScript project
898
- - `yarn validate` - Run full validation (lint + test + build)
899
-
900
- Read the project's [contributing guide](./CONTRIBUTING.md) for detailed development setup, testing guidelines, and contribution requirements.
901
-
902
- ## 🙏 Sponsor
903
-
904
- Like this project? **Leave a star**! ⭐⭐⭐⭐⭐
905
-
906
- There are several ways you can support this project:
907
-
908
- - [Become a sponsor](https://github.com/sponsors/wgtechlabs) and get some perks! 💖
909
- - [Buy me a coffee](https://buymeacoffee.com/wgtechlabs) if you just love what I do! ☕
910
-
911
- ## ⭐ GitHub Star Nomination
912
-
913
- Found this project helpful? Consider nominating me **(@warengonzaga)** for the [GitHub Star program](https://stars.github.com/nominate/)! This recognition supports ongoing development of this project and [my other open-source projects](https://github.com/warengonzaga?tab=repositories). GitHub Stars are recognized for their significant contributions to the developer community - your nomination makes a difference and encourages continued innovation!
914
-
915
- ## 📋 Code of Conduct
916
-
917
- I'm committed to providing a welcoming and inclusive environment for all contributors and users. Please review the project's [Code of Conduct](./code_of_conduct.md) to understand the community standards and expectations for participation.
918
-
919
- ## 📃 License
920
-
921
- This project is licensed under the [MIT License](https://opensource.org/licenses/MIT). See the [LICENSE](LICENSE) file for the full license text.
922
-
923
- ## 📝 Author
924
-
925
- This project is created by **[Waren Gonzaga](https://github.com/warengonzaga)** under [WG Technology Labs](https://github.com/wgtechlabs), with the help of awesome [contributors](https://github.com/wgtechlabs/log-engine/graphs/contributors).
926
-
927
- **Latest Version:** v2.2.0 - Enhanced with advanced output handlers, comprehensive security-first logging, complete TypeScript support, and extensive test coverage for local development workflows.
928
-
929
- [![contributors](https://contrib.rocks/image?repo=wgtechlabs/log-engine)](https://github.com/wgtechlabs/log-engine/graphs/contributors)
930
-
931
- ---
932
-
933
- đŸ’ģ with â¤ī¸ by [Waren Gonzaga](https://warengonzaga.com) under [WG Technology Labs](https://wgtechlabs.com), and [Him](https://www.youtube.com/watch?v=HHrxS4diLew&t=44s) 🙏
934
-
935
- <!-- GitAds-Verify: O4MESJK7VTBCELWNTFQAWB5HDX57H9MS -->
1
+ # Log Engine 📜🚂 [![made by](https://img.shields.io/badge/made%20by-WG%20Tech%20Labs-0060a0.svg?logo=github&longCache=true&labelColor=181717&style=flat-square)](https://github.com/wgtechlabs)
2
+
3
+ [![codecov](https://img.shields.io/codecov/c/github/wgtechlabs/log-engine?token=PWRJTBVKQ9&style=flat-square&logo=codecov&labelColor=181717)](https://codecov.io/gh/wgtechlabs/log-engine) [![npm downloads](https://img.shields.io/npm/dm/%40wgtechlabs%2Flog-engine?style=flat-square&logo=npm&label=installs&labelColor=181717&color=%23CD0000)](https://www.npmjs.com/package/@wgtechlabs/log-engine) [![sponsors](https://img.shields.io/badge/sponsor-%E2%9D%A4-%23db61a2.svg?&logo=github&logoColor=white&labelColor=181717&style=flat-square)](https://github.com/sponsors/wgtechlabs) [![release](https://img.shields.io/github/release/wgtechlabs/log-engine.svg?logo=github&labelColor=181717&color=green&style=flat-square)](https://github.com/wgtechlabs/log-engine/releases) [![star](https://img.shields.io/github/stars/wgtechlabs/log-engine.svg?&logo=github&labelColor=181717&color=yellow&style=flat-square)](https://github.com/wgtechlabs/log-engine/stargazers) [![license](https://img.shields.io/github/license/wgtechlabs/log-engine.svg?&logo=github&labelColor=181717&style=flat-square)](https://github.com/wgtechlabs/log-engine/blob/main/license)
4
+
5
+ [![banner](https://raw.githubusercontent.com/wgtechlabs/log-engine/main/.github/assets/repo_banner.jpg)](https://github.com/wgtechlabs/log-engine)
6
+
7
+ WG's Log Engine is the **ultimate logging solution for Node.js developers** - a lightweight, battle-tested utility specifically engineered for Discord bots, Telegram bots, web servers, APIs, and server-side applications. Born from real-world development challenges and proven in production environments like the [Unthread Discord Bot](https://github.com/wgtechlabs/unthread-discord-bot/), Log Engine delivers enterprise-grade logging with zero complexity, beautiful color-coded console output, **revolutionary configurable output routing**, and **advanced automatic data redaction with comprehensive PII protection**.
8
+
9
+ **The first logging library with built-in advanced PII protection, configurable output handlers, and comprehensive TypeScript support.** Stop wrestling with logging configurations and start building amazing applications safely. Whether you're creating the next viral Discord community bot, building high-performance APIs, developing microservices, or deploying production servers, Log Engine provides intelligent logging with vibrant colors, flexible output routing to any destination, advanced customizable redaction patterns, and automatic sensitive data protection that scales with your application's growth - from your first "Hello World" to handling millions of requests across distributed systems.
10
+
11
+ ## âŖī¸ Motivation
12
+
13
+ Picture this: It's 2 AM, your server is crashing in production, and you're staring at a terminal filled with thousands of debug messages mixed with critical errors. Sound familiar? I've been there too many times. I created Log Engine because every developer deserves to sleep peacefully, knowing their logs are working intelligently in the background.
14
+
15
+ Log Engine transforms your development experience from chaotic debugging sessions into confident, data-driven problem solving. No more guessing what went wrong, no more drowning in irrelevant logs, no more manual configuration headaches. Just clear, contextual information exactly when and where you need it. Because great applications deserve great logging, and great developers deserve tools that just work.
16
+
17
+ ## ✨ Key Features
18
+
19
+ - **🔒 Advanced Data Redaction (Enhanced!)**: Built-in PII protection with **custom regex patterns**, **dynamic field management**, and **environment-based configuration** - the first logging library with comprehensive security-first logging by default.
20
+ - **đŸŽ¯ Configurable Output Handlers (New!)**: Revolutionary output routing system supporting **custom destinations**, **multiple simultaneous outputs**, and **production-ready handlers** - redirect logs to files, HTTP endpoints, GUI applications, testing frameworks, or any custom destination with zero configuration complexity.
21
+ - **⚡ Custom Redaction Patterns**: Add your own regex patterns for advanced field detection and enterprise-specific data protection requirements.
22
+ - **đŸŽ¯ Dynamic Field Management**: Runtime configuration of sensitive fields with case-insensitive matching and partial field name detection.
23
+ - **đŸ› ī¸ Developer-Friendly API**: Advanced redaction methods including `testFieldRedaction()`, `withoutRedaction()`, and comprehensive configuration management.
24
+ - **📊 Comprehensive TypeScript Support**: Full type definitions with 15+ interfaces covering all functionality for maximum developer experience and IDE support.
25
+ - **🚀 Lightweight & Fast**: Minimal overhead with maximum performance - designed to enhance your application, not slow it down.
26
+ - **📚 No Learning Curve**: Dead simple API that you can master in seconds. No extensive documentation, complex configurations, or setup required - Log Engine works instantly.
27
+ - **🌈 Colorized Console Output**: Beautiful ANSI color-coded log levels with intelligent terminal formatting - instantly identify message severity at a glance with color-coded output.
28
+ - **đŸŽ›ī¸ Multiple Log Modes**: Support for DEBUG, INFO, WARN, ERROR, SILENT, OFF, and special LOG levels with smart filtering - just set your mode and let it handle the rest.
29
+ - **âš™ī¸ Auto-Configuration**: Intelligent environment-based setup using NODE_ENV variables. No config files, initialization scripts, or manual setup - Log Engine works perfectly out of the box.
30
+ - **✨ Enhanced Formatting**: Structured log entries with dual timestamps (ISO + human-readable) and colored level indicators for maximum readability.
31
+ - **🔗 Zero Dependencies**: No external dependencies for maximum compatibility and security - keeps your bundle clean and your project simple.
32
+ - **🔌 Easy Integration**: Simple API that works seamlessly with existing Node.js applications. Just `import` and start logging - no middleware, plugins, or configuration required.
33
+
34
+ ## âš ī¸ Breaking Changes Notice
35
+
36
+ **v3.0.0 Breaking Change**: The legacy `level` configuration will be removed in v3.0.0. If you're using `LogEngine.configure({ level: LogLevel.DEBUG })`, please migrate to `LogEngine.configure({ mode: LogMode.DEBUG })`. See our [Migration Guide](#migration-guide-loglevel--logmode) for details.
37
+
38
+ ## 🤔 How It Works
39
+ <!-- markdownlint-disable MD051 -->
40
+ 1. Log Engine automatically detects your environment using `NODE_ENV` and sets appropriate log levels for optimal performance
41
+ 2. When you call logging methods, messages are filtered based on the configured severity level (only messages at or above the set level are displayed)
42
+ 3. Each log message is instantly formatted with precise timestamps in both ISO and human-readable formats
43
+ 4. Messages are output to the console with **colorized level indicators and timestamps**, making debugging and monitoring effortless - errors show in red, warnings in yellow, info in blue, and debug in purple
44
+ 5. ANSI color codes ensure compatibility across different terminal environments while maintaining beautiful, readable output
45
+
46
+ Ready to streamline your application logging? Get started in seconds with our [simple installation](#đŸ“Ļ-installation)!
47
+ <!-- markdownlint-enable MD051 -->
48
+ ## 🤗 Special Thanks
49
+
50
+ <!-- markdownlint-disable MD033 -->
51
+ | <div align="center">💎 Platinum Sponsor</div> |
52
+ |:-------------------------------------------:|
53
+ | <a href="https://unthread.com"><img src="https://raw.githubusercontent.com/wgtechlabs/unthread-discord-bot/main/.github/assets/sponsors/platinum_unthread.png" width="250" alt="Unthread"></a> |
54
+ | <div align="center"><a href="https://unthread.com" target="_blank"><b>Unthread</b></a><br/>Streamlined support ticketing for modern teams.</div> |
55
+ <!-- markdownlint-enable MD033 -->
56
+
57
+ ## 💸 Sponsored Ads
58
+
59
+ Open source development is resource-intensive. These **sponsored ads help keep Log Engine free and actively maintained** while connecting you with tools and services that support open-source development.
60
+
61
+ [![sponsored ads](https://gitads.dev/v1/ad-serve?source=wgtechlabs/log-engine@github)](https://gitads.dev/v1/ad-track?source=wgtechlabs/log-engine@github)
62
+
63
+ ## đŸ“Ļ Installation
64
+
65
+ Install the package using pnpm (recommended):
66
+
67
+ ```bash
68
+ pnpm add @wgtechlabs/log-engine
69
+ ```
70
+
71
+ Or using npm:
72
+
73
+ ```bash
74
+ npm install @wgtechlabs/log-engine
75
+ ```
76
+
77
+ Or using yarn:
78
+
79
+ ```bash
80
+ yarn add @wgtechlabs/log-engine
81
+ ```
82
+
83
+ > **Note**: This project uses pnpm as the primary package manager for development. If you're contributing to the project, please use pnpm to ensure consistency with the development environment.
84
+
85
+ ## đŸ•šī¸ Usage
86
+
87
+ > **âš ī¸ Important**: If you're using the legacy `level` configuration, please migrate to `mode`. The `level` configuration is deprecated and will be removed in v3.0.0. See the [Migration Guide](#migration-guide-loglevel--logmode) below.
88
+
89
+ ### Quick Start
90
+
91
+ ```typescript
92
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
93
+
94
+ // Basic usage with auto-configuration based on NODE_ENV
95
+ LogEngine.debug('This is a debug message');
96
+ LogEngine.info('This is an info message');
97
+ LogEngine.warn('This is a warning message');
98
+ LogEngine.error('This is an error message');
99
+ LogEngine.log('This is a critical message that always shows');
100
+
101
+ // Advanced automatic data redaction (no configuration needed!)
102
+ LogEngine.info('User login', {
103
+ username: 'john_doe', // ✅ Visible
104
+ password: 'secret123', // ❌ [REDACTED]
105
+ email: 'john@example.com', // ❌ [REDACTED]
106
+ apiKey: 'apikey123' // ❌ [REDACTED]
107
+ });
108
+
109
+ // Advanced redaction features - Add custom patterns
110
+ LogEngine.addCustomRedactionPatterns([/internal.*/i, /company.*/i]);
111
+ LogEngine.addSensitiveFields(['companySecret', 'internalToken']);
112
+
113
+ // Test field redaction
114
+ console.log(LogEngine.testFieldRedaction('password')); // true
115
+ console.log(LogEngine.testFieldRedaction('username')); // false
116
+
117
+ // Raw logging for debugging (bypasses redaction)
118
+ LogEngine.withoutRedaction().info('Debug data', { password: 'visible-in-debug' });
119
+
120
+ // NEW: Custom output destinations (v2.0+)
121
+ LogEngine.configure({
122
+ outputHandler: (level, message, data) => {
123
+ // Send logs anywhere: GUI apps, files, APIs, databases
124
+ myCustomHandler(level, message, data);
125
+ },
126
+ suppressConsoleOutput: true // Optional: disable console
127
+ });
128
+
129
+ // NEW: Multiple outputs simultaneously
130
+ LogEngine.configure({
131
+ outputs: [
132
+ 'console', // Built-in console
133
+ myFileHandler, // Custom file handler
134
+ myMonitoringHandler // Custom monitoring
135
+ ]
136
+ });
137
+ ```
138
+
139
+ ### Mode-Based Configuration (Recommended)
140
+
141
+ Log Engine now uses a modern **LogMode** system that separates message severity from output control:
142
+
143
+ ```typescript
144
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
145
+
146
+ // Configure using LogMode (recommended approach)
147
+ LogEngine.configure({ mode: LogMode.DEBUG }); // Most verbose
148
+ LogEngine.configure({ mode: LogMode.INFO }); // Balanced
149
+ LogEngine.configure({ mode: LogMode.WARN }); // Focused
150
+ LogEngine.configure({ mode: LogMode.ERROR }); // Minimal
151
+ LogEngine.configure({ mode: LogMode.SILENT }); // Critical only
152
+ LogEngine.configure({ mode: LogMode.OFF }); // Complete silence
153
+
154
+ // Environment-based configuration example
155
+ const env = process.env.NODE_ENV || 'development';
156
+
157
+ if (env === 'production') {
158
+ LogEngine.configure({ mode: LogMode.INFO });
159
+ } else if (env === 'staging') {
160
+ LogEngine.configure({ mode: LogMode.WARN });
161
+ } else {
162
+ LogEngine.configure({ mode: LogMode.DEBUG });
163
+ }
164
+
165
+ // Now use Log Engine - only messages appropriate for the mode will be shown
166
+ LogEngine.debug('This will only show in DEBUG mode');
167
+ LogEngine.info('General information');
168
+ LogEngine.warn('Warning message');
169
+ LogEngine.error('Error message');
170
+ LogEngine.log('Critical message that always shows');
171
+ ```
172
+
173
+ ### Legacy Level-Based Configuration (âš ī¸ Deprecated)
174
+
175
+ **âš ī¸ DEPRECATION WARNING**: The `level` configuration is deprecated and will be removed in **v3.0.0**. Please use `mode` instead.
176
+
177
+ For backwards compatibility, the old `LogLevel` API is still supported but shows deprecation warnings:
178
+
179
+ ```typescript
180
+ import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
181
+
182
+ // âš ī¸ DEPRECATED: Legacy configuration (shows warning, will be removed in v3.0.0)
183
+ LogEngine.configure({ level: LogLevel.DEBUG }); // Triggers deprecation warning
184
+ LogEngine.configure({ level: LogLevel.INFO }); // Triggers deprecation warning
185
+ LogEngine.configure({ level: LogLevel.WARN }); // Triggers deprecation warning
186
+ LogEngine.configure({ level: LogLevel.ERROR }); // Triggers deprecation warning
187
+
188
+ // ✅ RECOMMENDED: Use the modern LogMode API instead
189
+ LogEngine.configure({ mode: LogMode.DEBUG }); // No warnings, future-proof
190
+ ```
191
+
192
+ **Why migrate to LogMode?**
193
+
194
+ - No deprecation warnings
195
+ - Future-proof API that won't be removed
196
+ - Better separation of concerns
197
+ - Access to all v2.0+ features including output handlers
198
+ - Clearer, more intuitive configuration
199
+
200
+ ### Migration Guide: LogLevel → LogMode
201
+
202
+ **âš ī¸ IMPORTANT DEPRECATION NOTICE**: The `level` configuration is **deprecated as of v2.0.0** and will be **removed in v3.0.0**. Please migrate to the new `mode` configuration.
203
+
204
+ **Version 1.2.0+** introduces the new LogMode system for better separation of concerns. Here's how to migrate:
205
+
206
+ ```typescript
207
+ // ❌ OLD (v1.1.0 and earlier) - DEPRECATED, will be removed in v3.0.0
208
+ import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
209
+ LogEngine.configure({ level: LogLevel.DEBUG }); // Shows deprecation warning
210
+
211
+ // ✅ NEW (v2.0.0+) - recommended approach with advanced features
212
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
213
+ LogEngine.configure({ mode: LogMode.DEBUG }); // Modern, future-proof API
214
+ ```
215
+
216
+ **Migration Benefits:**
217
+
218
+ **Key Benefits of LogMode:**
219
+
220
+ - **Clearer API**: Separates message severity (`LogLevel`) from output control (`LogMode`)
221
+ - **Better Environment Defaults**: `development→DEBUG`, `staging→WARN`, `test→ERROR`
222
+ - **Advanced Features**: New redaction APIs and TypeScript interfaces work with LogMode
223
+ - **Future-Proof**: All new features use the LogMode system
224
+ - **100% Backwards Compatible**: Existing code continues to work unchanged (with deprecation warnings)
225
+ - **No Breaking Changes in v2.0**: Legacy `level` support maintained until v3.0.0
226
+
227
+ ### Color-Coded Output 🎨
228
+
229
+ Log Engine now features beautiful, color-coded console output that makes debugging and monitoring a breeze:
230
+
231
+ ```typescript
232
+ import { LogEngine } from '@wgtechlabs/log-engine';
233
+
234
+ // Each log level gets its own distinct color for instant recognition
235
+ LogEngine.debug('🔍 Debugging user authentication flow'); // Purple/Magenta
236
+ LogEngine.info('â„šī¸ User successfully logged in'); // Blue
237
+ LogEngine.warn('âš ī¸ API rate limit at 80% capacity'); // Yellow
238
+ LogEngine.error('❌ Database connection timeout'); // Red
239
+ LogEngine.log('🚀 Application started successfully'); // Green
240
+ ```
241
+
242
+ **Why Colors Matter:**
243
+
244
+ - **Instant Recognition**: Quickly spot errors, warnings, and debug info without reading every line
245
+ - **Better Debugging**: Visually separate different types of messages during development
246
+ - **Production Monitoring**: Easily scan logs for critical issues in terminal environments
247
+ - **Enhanced Readability**: Color-coded timestamps and level indicators reduce eye strain
248
+
249
+ ### Log Modes
250
+
251
+ Log Engine uses a **LogMode** system that controls output verbosity and filtering:
252
+
253
+ - `LogMode.DEBUG` (0) - Most verbose: shows DEBUG, INFO, WARN, ERROR, LOG messages
254
+ - `LogMode.INFO` (1) - Balanced: shows INFO, WARN, ERROR, LOG messages
255
+ - `LogMode.WARN` (2) - Focused: shows WARN, ERROR, LOG messages
256
+ - `LogMode.ERROR` (3) - Minimal: shows ERROR, LOG messages
257
+ - `LogMode.SILENT` (4) - Critical only: shows LOG messages only
258
+ - `LogMode.OFF` (5) - Complete silence: shows no messages at all
259
+
260
+ ### Message Severity Levels
261
+
262
+ Individual log messages have severity levels that determine their importance:
263
+
264
+ - `LogLevel.DEBUG` (0) - Detailed information for debugging
265
+ - `LogLevel.INFO` (1) - General information
266
+ - `LogLevel.WARN` (2) - Warning messages
267
+ - `LogLevel.ERROR` (3) - Error messages
268
+ - `LogLevel.LOG` (99) - Critical messages that always show (except when OFF mode is set)
269
+
270
+ ### Auto-Configuration
271
+
272
+ Log Engine automatically configures itself based on the `NODE_ENV` environment variable:
273
+
274
+ - `development` → `LogMode.DEBUG` (most verbose)
275
+ - `production` → `LogMode.INFO` (balanced)
276
+ - `staging` → `LogMode.WARN` (focused)
277
+ - `test` → `LogMode.ERROR` (minimal)
278
+ - `default` → `LogMode.INFO` (balanced)
279
+
280
+ ### Special LOG Level
281
+
282
+ The `LOG` level is special and behaves differently from other levels:
283
+
284
+ - **Always Visible**: LOG messages are always displayed regardless of the configured log mode (except when OFF mode is set)
285
+ - **Critical Information**: Perfect for essential system messages, application lifecycle events, and operational information that must never be filtered out
286
+ - **Green Color**: Uses green coloring to distinguish it from other levels
287
+ - **Use Cases**: Application startup/shutdown, server listening notifications, critical configuration changes, deployment information
288
+
289
+ ```typescript
290
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
291
+
292
+ // Even with SILENT mode, LOG messages still appear
293
+ LogEngine.configure({ mode: LogMode.SILENT });
294
+
295
+ LogEngine.debug('Debug message'); // Hidden
296
+ LogEngine.info('Info message'); // Hidden
297
+ LogEngine.warn('Warning message'); // Hidden
298
+ LogEngine.error('Error message'); // Hidden
299
+ LogEngine.log('Server started on port 3000'); // ✅ Always visible!
300
+
301
+ // But with OFF mode, even LOG messages are hidden
302
+ LogEngine.configure({ mode: LogMode.OFF });
303
+ LogEngine.log('This LOG message is hidden'); // ❌ Hidden with OFF mode
304
+ ```
305
+
306
+ ### Complete Silence with OFF Mode
307
+
308
+ The `OFF` mode provides complete logging silence when you need to disable all output:
309
+
310
+ - **Total Silence**: Disables ALL logging including the special LOG level messages
311
+ - **Testing & CI/CD**: Perfect for automated testing environments where no console output is desired
312
+ - **Performance**: Minimal overhead when logging is completely disabled
313
+ - **Use Cases**: Unit tests, CI/CD pipelines, production environments requiring zero log output
314
+
315
+ ```typescript
316
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
317
+
318
+ // Comparison: SILENT vs OFF
319
+ LogEngine.configure({ mode: LogMode.SILENT });
320
+ LogEngine.info('Info message'); // Hidden
321
+ LogEngine.log('Critical message'); // ✅ Still visible with SILENT
322
+
323
+ LogEngine.configure({ mode: LogMode.OFF });
324
+ LogEngine.info('Info message'); // Hidden
325
+ LogEngine.log('Critical message'); // ❌ Hidden with OFF - complete silence!
326
+ ```
327
+
328
+ ### Log Format
329
+
330
+ Log messages are beautifully formatted with colorized timestamps, levels, and smart terminal output:
331
+
332
+ ```bash
333
+ # Example colorized output (colors visible in terminal)
334
+ [2025-05-29T16:57:45.678Z][4:57PM][DEBUG]: Debugging application flow
335
+ [2025-05-29T16:57:46.123Z][4:57PM][INFO]: Server started successfully
336
+ [2025-05-29T16:57:47.456Z][4:57PM][WARN]: API rate limit approaching
337
+ [2025-05-29T16:57:48.789Z][4:57PM][ERROR]: Database connection failed
338
+ [2025-05-29T16:57:49.012Z][4:57PM][LOG]: Application startup complete
339
+ ```
340
+
341
+ **Color Scheme:**
342
+
343
+ - đŸŸŖ **DEBUG**: Magenta/Purple - Detailed debugging information
344
+ - đŸ”ĩ **INFO**: Blue - General informational messages
345
+ - 🟡 **WARN**: Yellow - Warning messages that need attention
346
+ - 🔴 **ERROR**: Red - Error messages requiring immediate action
347
+ - đŸŸĸ **LOG**: Green - Critical messages that always display
348
+ - âšĢ **Timestamps**: Gray (ISO) and Cyan (local time) for easy scanning
349
+
350
+ ### Customizing Log Elements
351
+
352
+ **LogEngine v2.1+ introduces the ability to customize which elements are included in your log output** while keeping log levels mandatory for clarity and consistency.
353
+
354
+ #### Available Customization Options
355
+
356
+ You can control the inclusion of timestamp elements:
357
+
358
+ - **ISO Timestamp**: `[2025-05-29T16:57:45.678Z]` - Precise UTC timestamp
359
+ - **Local Time**: `[4:57PM]` - Human-readable local time
360
+ - **Log Level**: `[INFO]` - Always included (non-customizable as per design)
361
+
362
+ #### Format Configuration Examples
363
+
364
+ ```typescript
365
+ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
366
+
367
+ // Default format (backward compatible)
368
+ LogEngine.configure({ mode: LogMode.DEBUG });
369
+ LogEngine.info('Server started');
370
+ // Output: [2025-05-29T16:57:45.678Z][4:57PM][INFO]: Server started
371
+
372
+ // Only ISO timestamp
373
+ LogEngine.configure({
374
+ mode: LogMode.DEBUG,
375
+ format: {
376
+ includeIsoTimestamp: true,
377
+ includeLocalTime: false
378
+ }
379
+ });
380
+ LogEngine.info('Database connected');
381
+ // Output: [2025-05-29T16:57:45.678Z][INFO]: Database connected
382
+
383
+ // Only local time
384
+ LogEngine.configure({
385
+ mode: LogMode.DEBUG,
386
+ format: {
387
+ includeIsoTimestamp: false,
388
+ includeLocalTime: true
389
+ }
390
+ });
391
+ LogEngine.warn('Rate limit approaching');
392
+ // Output: [4:57PM][WARN]: Rate limit approaching
393
+
394
+ // Minimal format (no timestamps)
395
+ LogEngine.configure({
396
+ mode: LogMode.DEBUG,
397
+ format: {
398
+ includeIsoTimestamp: false,
399
+ includeLocalTime: false
400
+ }
401
+ });
402
+ LogEngine.error('Connection failed');
403
+ // Output: [ERROR]: Connection failed
404
+ ```
405
+
406
+ #### Benefits of Log Element Customization
407
+
408
+ - **đŸŽ¯ Reduced Verbosity**: Remove unnecessary timestamp information in containerized environments where external logging systems add timestamps
409
+ - **📱 Space Efficiency**: Minimize log line length for mobile or constrained display environments
410
+ - **🔧 Integration Ready**: Match existing log format requirements in your infrastructure
411
+ - **⚡ Performance**: Slightly reduced formatting overhead when timestamps are disabled
412
+ - **🔒 Backward Compatible**: Default behavior remains unchanged - existing code continues to work without modifications
413
+
414
+ **Note**: Log levels (`[DEBUG]`, `[INFO]`, `[WARN]`, `[ERROR]`, `[LOG]`) are always included regardless of configuration to maintain log clarity and filtering capabilities.
415
+
416
+ ## 🔒 Advanced Data Redaction
417
+
418
+ **LogEngine features comprehensive built-in PII protection with advanced customization capabilities that automatically redacts sensitive information from your logs.** This security-first approach prevents accidental exposure of passwords, tokens, emails, and other sensitive data while maintaining full debugging capabilities with enterprise-grade flexibility.
419
+
420
+ ### Zero Configuration Security
421
+
422
+ Just use LogEngine normally - **sensitive data is automatically protected**:
423
+
424
+ ```typescript
425
+ import { LogEngine } from '@wgtechlabs/log-engine';
426
+
427
+ // ✅ Automatic redaction - no setup needed!
428
+ LogEngine.info('User authentication', {
429
+ username: 'john_doe', // ✅ Visible
430
+ password: 'secret123', // ❌ [REDACTED]
431
+ email: 'john@example.com', // ❌ [REDACTED]
432
+ apiKey: 'apikey123', // ❌ [REDACTED]
433
+ timestamp: new Date() // ✅ Visible
434
+ });
435
+
436
+ // Output: [INFO]: User authentication {"username":"john_doe","password":"[REDACTED]","email":"[REDACTED]","apiKey":"[REDACTED]","timestamp":"2025-06-17T..."}
437
+ ```
438
+
439
+ ### Protected Data Types
440
+
441
+ **50+ sensitive patterns automatically detected:**
442
+
443
+ - **Authentication**: `password`, `token`, `apiKey`, `secret`, `jwt`, `auth`, `sessionId`
444
+ - **Personal Info**: `email`, `phone`, `ssn`, `firstName`, `lastName`, `address`
445
+ - **Financial**: `creditCard`, `cvv`, `bankAccount`, `routingNumber`
446
+ - **System**: `clientSecret`, `privateKey`, `webhookSecret`
447
+
448
+ ### Deep Object Scanning
449
+
450
+ Automatically scans nested objects and arrays:
451
+
452
+ ```typescript
453
+ LogEngine.warn('Payment processing', {
454
+ order: {
455
+ id: 'order-123', // ✅ Visible
456
+ customer: {
457
+ username: 'customer1', // ✅ Visible
458
+ email: 'user@example.com', // ❌ [REDACTED]
459
+ creditCard: '4532-****' // ❌ [REDACTED]
460
+ }
461
+ },
462
+ metadata: {
463
+ processor: 'stripe',
464
+ apiSecret: 'sk_live_...' // ❌ [REDACTED]
465
+ }
466
+ });
467
+ ```
468
+
469
+ ### Content Truncation
470
+
471
+ Large content fields are automatically truncated to prevent log bloat:
472
+
473
+ ```typescript
474
+ LogEngine.debug('Large payload', {
475
+ content: 'Very long content...'.repeat(100), // Truncated at 100 chars + "... [TRUNCATED]"
476
+ size: 'large',
477
+ processed: true
478
+ });
479
+ ```
480
+
481
+ ### Development-Friendly Features
482
+
483
+ **Raw Methods for Debugging:**
484
+
485
+ ```typescript
486
+ // âš ī¸ Use with caution - bypasses redaction
487
+ LogEngine.debugRaw('Full debug data', {
488
+ password: 'secret123', // âš ī¸ Visible (not redacted)
489
+ apiKey: 'full-key' // âš ī¸ Visible (not redacted)
490
+ });
491
+
492
+ // Or use the helper method
493
+ LogEngine.withoutRedaction().info('Debug mode', sensitiveData);
494
+ ```
495
+
496
+ **Environment-Based Control:**
497
+
498
+ ```bash
499
+ # Development - show everything (redaction disabled)
500
+ NODE_ENV=development
501
+
502
+ # Explicitly disable redaction
503
+ LOG_REDACTION_DISABLED=true
504
+ DEBUG_FULL_PAYLOADS=true
505
+
506
+ # Custom redaction configuration
507
+ LOG_REDACTION_TEXT="***CONFIDENTIAL***"
508
+ LOG_MAX_CONTENT_LENGTH=200
509
+ LOG_SENSITIVE_FIELDS="customField,companySecret,internalData"
510
+ LOG_TRUNCATION_TEXT="... [CUSTOM_TRUNCATED]"
511
+
512
+ # Advanced environment integration
513
+ LOG_REDACTION_ENABLED=false # Alternative disable method
514
+ ```
515
+
516
+ ### Custom Configuration
517
+
518
+ **Modify redaction behavior:**
519
+
520
+ ```typescript
521
+ // Custom redaction settings
522
+ LogEngine.configureRedaction({
523
+ redactionText: '***HIDDEN***',
524
+ maxContentLength: 200,
525
+ sensitiveFields: ['myCustomField', 'internalSecret']
526
+ });
527
+
528
+ // Get current configuration
529
+ const config = LogEngine.getRedactionConfig();
530
+ console.log(config);
531
+ ```
532
+
533
+ ### Advanced Redaction Features (v1.2.1+)
534
+
535
+ **Custom Patterns & Dynamic Field Management:**
536
+
537
+ ```typescript
538
+ // Add custom regex patterns for enterprise-specific data protection
539
+ LogEngine.addCustomRedactionPatterns([
540
+ /internal.*/i, // Matches any field starting with "internal"
541
+ /company.*/i, // Matches any field starting with "company"
542
+ /^config[A-Z]/ // Matches camelCase config fields
543
+ ]);
544
+
545
+ // Add custom sensitive field names dynamically
546
+ LogEngine.addSensitiveFields(['companySecret', 'internalToken', 'proprietaryData']);
547
+
548
+ // Test field redaction before logging
549
+ if (LogEngine.testFieldRedaction('myField')) {
550
+ console.log('Field will be redacted');
551
+ }
552
+
553
+ // Advanced configuration management
554
+ LogEngine.configureRedaction({
555
+ redactionText: '***CONFIDENTIAL***',
556
+ maxContentLength: 150,
557
+ customPatterns: [/private.*/i, /secret.*/i]
558
+ });
559
+
560
+ // Configuration utilities
561
+ const currentConfig = LogEngine.getRedactionConfig();
562
+ LogEngine.refreshRedactionConfig(); // Refresh from environment
563
+ LogEngine.resetRedactionConfig(); // Reset to defaults
564
+ LogEngine.clearCustomRedactionPatterns(); // Clear custom patterns
565
+ ```
566
+
567
+ **Enhanced Development Workflow:**
568
+
569
+ ```typescript
570
+ // Raw logging methods (bypass redaction) - use with caution
571
+ LogEngine.debugRaw('Full debug data', { password: 'visible', apiKey: 'full-key' });
572
+
573
+ // Temporary redaction bypass using helper method
574
+ LogEngine.withoutRedaction().info('Debug mode', sensitiveData);
575
+
576
+ // Compare outputs during development
577
+ LogEngine.info('With redaction', data); // ❌ [REDACTED]
578
+ LogEngine.withoutRedaction().info('Without redaction', data); // âš ī¸ Visible
579
+ ```
580
+
581
+ ### Environment Behavior
582
+
583
+ | Environment | Redaction Status | Use Case |
584
+ |-------------|------------------|----------|
585
+ | **Production** | 🔒 **Active** | Full protection for live systems |
586
+ | **Development** | đŸ› ī¸ **Disabled** | Full data visibility for debugging |
587
+ | **Staging** | 🔒 **Active** | Test with production-like security |
588
+ | **Test** | 🔒 **Active** | Consistent test environment |
589
+
590
+ ### Security Benefits
591
+
592
+ ✅ **Advanced Pattern Recognition** - Custom regex patterns for enterprise-specific data protection
593
+ ✅ **Dynamic Field Management** - Runtime configuration of sensitive fields with intelligent matching
594
+ ✅ **Comprehensive Testing API** - `testFieldRedaction()` for validation and debugging
595
+ ✅ **Environment Integration** - Seamless configuration via environment variables
596
+ ✅ **Development Workflow** - Raw logging methods and temporary redaction bypass for debugging
597
+ ✅ **Prevents Data Leaks** - Automatic protection against accidental exposure with 50+ built-in patterns
598
+ ✅ **Compliance Ready** - Helps meet GDPR, HIPAA, and other privacy requirements
599
+ ✅ **Zero Configuration** - Secure by default, advanced features when needed
600
+ ✅ **Performance Optimized** - Minimal overhead with intelligent processing and depth limiting
601
+ ✅ **TypeScript Excellence** - Full type safety with comprehensive interfaces and type definitions
602
+
603
+ **Perfect for:** Enterprise applications, compliance requirements, team development environments, production systems requiring both security and debugging flexibility, and any scenario where sensitive data protection is critical.
604
+
605
+ ## đŸŽ¯ Configurable Output Handlers
606
+
607
+ **LogEngine v2.0+ introduces revolutionary output routing capabilities that transform how and where your logs are delivered.** This powerful system enables custom log destinations, multiple simultaneous outputs, and production-ready handlers while maintaining the same simple API you know and love.
608
+
609
+ ### Zero-Configuration Custom Routing
610
+
611
+ **Redirect logs anywhere with a single configuration:**
612
+
613
+ ```typescript
614
+ import { LogEngine } from '@wgtechlabs/log-engine';
615
+
616
+ // Redirect to GUI application
617
+ LogEngine.configure({
618
+ outputHandler: (level, message, data) => {
619
+ updateReactUI({ level, message, timestamp: new Date() });
620
+ },
621
+ suppressConsoleOutput: true // Optional: disable console output
622
+ });
623
+
624
+ // Testing framework integration
625
+ const capturedLogs = [];
626
+ LogEngine.configure({
627
+ outputHandler: (level, message, data) => {
628
+ capturedLogs.push({ level, message, data });
629
+ },
630
+ suppressConsoleOutput: true
631
+ });
632
+
633
+ // Now use LogEngine normally - output goes to your custom handler
634
+ LogEngine.info('User logged in', { userId: 123 });
635
+ ```
636
+
637
+ ### Multiple Simultaneous Outputs
638
+
639
+ **Log to multiple destinations at once with built-in handlers:**
640
+
641
+ ```typescript
642
+ LogEngine.configure({
643
+ outputs: [
644
+ 'console', // Built-in console handler
645
+ 'silent', // Built-in silent handler (no output)
646
+ (level, message, data) => {
647
+ // Custom file handler
648
+ fs.appendFileSync('./app.log', `${new Date().toISOString()} [${level}] ${message}\n`);
649
+ },
650
+ (level, message, data) => {
651
+ // Custom network handler
652
+ if (level === 'error') {
653
+ sendToMonitoringService({ level, message, data });
654
+ }
655
+ }
656
+ ]
657
+ });
658
+
659
+ // Single log call outputs to all configured destinations
660
+ LogEngine.error('Database connection failed', { retries: 3 });
661
+ ```
662
+
663
+ ### Production-Ready Advanced Handlers
664
+
665
+ **Enterprise-grade file and HTTP outputs with advanced features:**
666
+
667
+ ```typescript
668
+ LogEngine.configure({
669
+ enhancedOutputs: [
670
+ 'console',
671
+ {
672
+ type: 'file',
673
+ config: {
674
+ filePath: './logs/app.log',
675
+ maxFileSize: 10485760, // 10MB rotation
676
+ maxBackupFiles: 5, // Keep 5 backup files
677
+ append: true, // Append mode
678
+ formatter: (level, message, data) => {
679
+ const timestamp = new Date().toISOString();
680
+ const dataStr = data ? ` | ${JSON.stringify(data)}` : '';
681
+ return `[${timestamp}] ${level.toUpperCase()}: ${message}${dataStr}\n`;
682
+ }
683
+ }
684
+ },
685
+ {
686
+ type: 'http',
687
+ config: {
688
+ url: 'https://api.datadog.com/v1/logs',
689
+ method: 'POST',
690
+ batchSize: 10, // Batch requests for performance
691
+ timeout: 5000, // 5-second timeout
692
+ headers: {
693
+ 'Authorization': 'Bearer your-api-key',
694
+ 'Content-Type': 'application/json'
695
+ },
696
+ formatter: (logs) => ({
697
+ service: 'my-app',
698
+ environment: process.env.NODE_ENV,
699
+ logs: logs.map(log => ({
700
+ timestamp: log.timestamp,
701
+ level: log.level,
702
+ message: log.message,
703
+ metadata: log.data
704
+ }))
705
+ })
706
+ }
707
+ }
708
+ ]
709
+ });
710
+ ```
711
+
712
+ ### Configuration Priority System
713
+
714
+ **Flexible configuration with intelligent priority handling:**
715
+
716
+ ```typescript
717
+ // Priority: outputs > enhancedOutputs > outputHandler > default console
718
+
719
+ // Single handler (legacy compatibility)
720
+ LogEngine.configure({
721
+ outputHandler: myHandler,
722
+ suppressConsoleOutput: true
723
+ });
724
+
725
+ // Multiple basic outputs - takes priority over outputHandler
726
+ LogEngine.configure({
727
+ outputs: ['console', myFileHandler, myNetworkHandler]
728
+ });
729
+
730
+ // Advanced outputs - used when outputs not specified
731
+ LogEngine.configure({
732
+ enhancedOutputs: [
733
+ 'console',
734
+ { type: 'file', config: { filePath: './app.log' } }
735
+ ]
736
+ });
737
+ ```
738
+
739
+ ### Error Handling & Resilience
740
+
741
+ **Robust error handling ensures logging never breaks your application:**
742
+
743
+ ```typescript
744
+ LogEngine.configure({
745
+ outputs: [
746
+ 'console', // Always works
747
+ (level, message) => {
748
+ throw new Error('Handler failed'); // This failure won't break other outputs
749
+ },
750
+ (level, message) => {
751
+ fs.writeFileSync('./logs/app.log', message); // This still works
752
+ }
753
+ ]
754
+ });
755
+
756
+ // If any handler fails, others continue working + fallback to console
757
+ LogEngine.error('Critical error'); // Logs to console + working file handler
758
+ ```
759
+
760
+ ### Output Handler Benefits
761
+
762
+ ✅ **GUI Integration** - Perfect for desktop applications, web dashboards, and real-time monitoring
763
+ ✅ **Testing Support** - Capture and assert on log output in automated tests
764
+ ✅ **Production Monitoring** - Send logs to Datadog, New Relic, CloudWatch, or custom endpoints
765
+ ✅ **File Logging** - Persistent logs with automatic rotation and backup management
766
+ ✅ **Silent Operation** - Disable console output for clean CLI tools and background services
767
+ ✅ **Multi-Destination** - Log to console + file + network simultaneously with zero overhead
768
+ ✅ **Error Isolation** - Failed outputs don't break other outputs or your application
769
+ ✅ **Backward Compatible** - Existing code works unchanged, new features are opt-in only
770
+ ✅ **TypeScript Ready** - Full type safety with comprehensive interfaces and IntelliSense
771
+ ✅ **Zero Dependencies** - Built-in handlers use only Node.js standard library
772
+
773
+ **Use Cases:** Desktop applications, testing frameworks, production monitoring, CI/CD pipelines, microservices, IoT devices, and any scenario requiring flexible log routing with enterprise-grade reliability.
774
+
775
+ ## 📚 Comprehensive TypeScript Support
776
+
777
+ **LogEngine v2.0+ includes extensive TypeScript definitions with 15+ interfaces for maximum type safety and developer experience:**
778
+
779
+ ### Core Interfaces
780
+
781
+ ```typescript
782
+ import {
783
+ LogEngine,
784
+ LogMode,
785
+ LogLevel,
786
+ ILogEngine,
787
+ ILogEngineWithoutRedaction,
788
+ RedactionConfig,
789
+ LoggerConfig,
790
+ LogOutputHandler,
791
+ FileOutputConfig,
792
+ HttpOutputConfig,
793
+ IDataRedactor
794
+ } from '@wgtechlabs/log-engine';
795
+
796
+ // Full type safety for all methods
797
+ const config: RedactionConfig = {
798
+ enabled: true,
799
+ sensitiveFields: ['password', 'token'],
800
+ redactionText: '[HIDDEN]',
801
+ maxContentLength: 100,
802
+ // ... fully typed configuration
803
+ };
804
+
805
+ // Type-safe output handler configuration
806
+ const outputHandler: LogOutputHandler = (level, message, data) => {
807
+ console.log(`[${level}] ${message}`, data);
808
+ };
809
+
810
+ const fileConfig: FileOutputConfig = {
811
+ filePath: './app.log',
812
+ maxFileSize: 1048576,
813
+ maxBackupFiles: 3,
814
+ formatter: (level, message, data) => `${level}: ${message}\n`
815
+ };
816
+
817
+ // Advanced redaction testing with return types
818
+ const isRedacted: boolean = LogEngine.testFieldRedaction('password');
819
+ const currentConfig: RedactionConfig = LogEngine.getRedactionConfig();
820
+
821
+ // Type-safe raw logging
822
+ const rawLogger: ILogEngineWithoutRedaction = LogEngine.withoutRedaction();
823
+ rawLogger.info('Debug info', sensitiveData); // Fully typed methods
824
+
825
+ // âš ī¸ Legacy (deprecated) - will be removed in v3.0.0
826
+ import { LogLevel } from '@wgtechlabs/log-engine';
827
+ LogEngine.configure({ level: LogLevel.DEBUG }); // Shows deprecation warning
828
+ ```
829
+
830
+ ### Available Interfaces
831
+
832
+ - **`ILogEngine`** - Complete LogEngine API with all methods
833
+ - **`ILogEngineWithoutRedaction`** - Raw logging methods interface
834
+ - **`IDataRedactor`** - Static DataRedactor class methods
835
+ - **`LogOutputHandler`** - Custom output handler function interface
836
+ - **`FileOutputConfig`** - File output handler configuration
837
+ - **`HttpOutputConfig`** - HTTP output handler configuration
838
+ - **`RedactionConfig`** - Comprehensive redaction configuration
839
+ - **`LoggerConfig`** - Logger configuration options (including output handlers)
840
+ - **`LogEntry`** - Structured log entry interface
841
+ - **`LogLevel`** - âš ī¸ **Deprecated**: Legacy level enumeration (use `LogMode` instead)
842
+ - **`LogMode`** - ✅ **Recommended**: Modern mode enumeration
843
+ - **`EnvironmentConfig`** - Environment variable documentation
844
+ - **`EnvironmentConfig`** - Environment variable documentation
845
+ - **Plus 5+ additional interfaces** for advanced output handling and configuration
846
+
847
+ **IDE Benefits:** IntelliSense, auto-completion, parameter hints, error detection, and comprehensive documentation tooltips throughout your development workflow.
848
+
849
+ ## đŸ’Ŧ Community Discussions
850
+
851
+ Join our community discussions to get help, share ideas, and connect with other users:
852
+
853
+ - đŸ“Ŗ **[Announcements](https://github.com/wgtechlabs/log-engine/discussions/categories/announcements)**: Official updates from the maintainer
854
+ - 📸 **[Showcase](https://github.com/wgtechlabs/log-engine/discussions/categories/showcase)**: Show and tell your implementation
855
+ - 💖 **[Wall of Love](https://github.com/wgtechlabs/log-engine/discussions/categories/wall-of-love)**: Share your experience with the library
856
+ - 🛟 **[Help & Support](https://github.com/wgtechlabs/log-engine/discussions/categories/help-support)**: Get assistance from the community
857
+ - 🧠 **[Ideas](https://github.com/wgtechlabs/log-engine/discussions/categories/ideas)**: Suggest new features and improvements
858
+
859
+ ## 🛟 Help & Support
860
+
861
+ ### Getting Help
862
+
863
+ Need assistance with the library? Here's how to get help:
864
+ <!-- markdownlint-disable MD051 -->
865
+ - **Community Support**: Check the [Help & Support](https://github.com/wgtechlabs/log-engine/discussions/categories/help-support) category in our GitHub Discussions for answers to common questions.
866
+ - **Ask a Question**: Create a [new discussion](https://github.com/wgtechlabs/log-engine/discussions/new?category=help-support) if you can't find answers to your specific issue.
867
+ - **Documentation**: Review the [usage instructions](#đŸ•šī¸-usage) in this README for common examples and configurations.
868
+ - **Known Issues**: Browse [existing issues](https://github.com/wgtechlabs/log-engine/issues) to see if your problem has already been reported.
869
+ <!-- markdownlint-enable MD051 -->
870
+
871
+ ### Reporting Issues
872
+
873
+ Please report any issues, bugs, or improvement suggestions by [creating a new issue](https://github.com/wgtechlabs/log-engine/issues/new/choose). Before submitting, please check if a similar issue already exists to avoid duplicates.
874
+
875
+ ### Security Vulnerabilities
876
+
877
+ For security vulnerabilities, please do not report them publicly. Follow the guidelines in our [security policy](./security.md) to responsibly disclose security issues.
878
+
879
+ Your contributions to improving this project are greatly appreciated! 🙏✨
880
+
881
+ ## đŸŽ¯ Contributing
882
+
883
+ Contributions are welcome, create a pull request to this repo and I will review your code. Please consider to submit your pull request to the `dev` branch. Thank you!
884
+
885
+ **Development Environment:**
886
+
887
+ - This project is configured for **local development workflows only** - no CI/CD setup required
888
+ - Uses **pnpm** as the primary package manager for consistency
889
+ - Simple, cross-platform development setup with TypeScript, Jest, and ESLint
890
+ - Clean test output maintained using `jest.setup.js` to suppress console noise during testing
891
+ - All error logging functionality remains intact in production code
892
+ - Security scanning available via Snyk for dependency vulnerability checking
893
+
894
+ **Available Scripts:**
895
+
896
+ - `pnpm test` - Run all tests
897
+ - `pnpm test:watch` - Run tests in watch mode
898
+ - `pnpm test:coverage` - Run tests with coverage reporting
899
+ - `pnpm lint` - Run TypeScript and code quality checks
900
+ - `pnpm lint:fix` - Automatically fix linting issues
901
+ - `pnpm lint:security` - Run security-focused linting
902
+ - `pnpm secure` - Run comprehensive security checks
903
+ - `pnpm build` - Build the TypeScript project
904
+ - `pnpm validate` - Run full validation (lint + test + build)
905
+
906
+ Read the project's [contributing guide](./CONTRIBUTING.md) for detailed development setup, testing guidelines, and contribution requirements.
907
+
908
+ ## 🙏 Sponsor
909
+
910
+ Like this project? **Leave a star**! ⭐⭐⭐⭐⭐
911
+
912
+ There are several ways you can support this project:
913
+
914
+ - [Become a sponsor](https://github.com/sponsors/wgtechlabs) and get some perks! 💖
915
+ - [Buy me a coffee](https://buymeacoffee.com/wgtechlabs) if you just love what I do! ☕
916
+
917
+ ## ⭐ GitHub Star Nomination
918
+
919
+ Found this project helpful? Consider nominating me **(@warengonzaga)** for the [GitHub Star program](https://stars.github.com/nominate/)! This recognition supports ongoing development of this project and [my other open-source projects](https://github.com/warengonzaga?tab=repositories). GitHub Stars are recognized for their significant contributions to the developer community - your nomination makes a difference and encourages continued innovation!
920
+
921
+ ## 📋 Code of Conduct
922
+
923
+ I'm committed to providing a welcoming and inclusive environment for all contributors and users. Please review the project's [Code of Conduct](./code_of_conduct.md) to understand the community standards and expectations for participation.
924
+
925
+ ## 📃 License
926
+
927
+ This project is licensed under the [MIT License](https://opensource.org/licenses/MIT). See the [LICENSE](LICENSE) file for the full license text.
928
+
929
+ ## 📝 Author
930
+
931
+ This project is created by **[Waren Gonzaga](https://github.com/warengonzaga)** under [WG Technology Labs](https://github.com/wgtechlabs), with the help of awesome [contributors](https://github.com/wgtechlabs/log-engine/graphs/contributors).
932
+
933
+ **Latest Version:** v2.1.0 - Enhanced with advanced output handlers, comprehensive security-first logging, complete TypeScript support, and 95%+ test coverage for local development workflows.
934
+
935
+ [![contributors](https://contrib.rocks/image?repo=wgtechlabs/log-engine)](https://github.com/wgtechlabs/log-engine/graphs/contributors)
936
+
937
+ ---
938
+
939
+ đŸ’ģ with â¤ī¸ by [Waren Gonzaga](https://warengonzaga.com) under [WG Technology Labs](https://wgtechlabs.com), and [Him](https://www.youtube.com/watch?v=HHrxS4diLew&t=44s) 🙏
940
+
941
+ <!-- GitAds-Verify: ATEXU25ZNQXEHHBSSKYIKDFHVSEEAMEF -->