@wgtechlabs/log-engine 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,28 +1,73 @@
1
- # Log Engine
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
2
 
3
- ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/wgtechlabs/log-engine/test.yml?branch=main&style=flat-square&logo=github&link=https%3A%2F%2Fgithub.com%2Fwgtechlabs%2Flog-engine%2Factions%2Fworkflows%2Ftest.yml) ![Codecov](https://img.shields.io/codecov/c/github/wgtechlabs/log-engine?token=PWRJTBVKQ9&style=flat-square&logo=codecov&link=https%3A%2F%2Fcodecov.io%2Fgh%2Fwgtechlabs%2Flog-engine)
3
+ [![github actions workflow status](https://img.shields.io/github/actions/workflow/status/wgtechlabs/log-engine/test.yml?branch=main&style=flat-square&logo=github&labelColor=181717)](https://github.com/wgtechlabs/log-engine/actions/workflows/test.yml) [![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/d18m/%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
4
 
5
- WG's Log Engine is a lightweight and efficient logging utility designed specifically for bot applications running on Node.js.
5
+ [![banner](https://raw.githubusercontent.com/wgtechlabs/log-engine/main/.github/assets/repo_banner.jpg)](https://github.com/wgtechlabs/log-engine)
6
6
 
7
- ## Features
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 and beautiful color-coded console output.
8
8
 
9
- - Log messages with timestamps
10
- - Support for multiple log levels: DEBUG, INFO, WARN, ERROR, SILENT
11
- - Configurable log level filtering
12
- - Environment-based auto-configuration
13
- - Easy integration into your Node.js applications
9
+ **Stop wrestling with logging configurations and start building amazing applications.** Whether you're creating the next viral Discord community bot, building high-performance APIs, developing microservices, or deploying production servers, Log Engine provides intelligent terminal-based logging with vibrant colors that scales with your application's growth - from your first "Hello World" to handling millions of requests across distributed systems.
14
10
 
15
- ## Installation
11
+ ## âŖī¸ Motivation
16
12
 
17
- To install the @wgtechlabs/log-engine package, run the following command:
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.
18
14
 
19
- ```
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
+ - **Lightweight & Fast**: Minimal overhead with maximum performance - designed to enhance your application, not slow it down.
20
+ - **No Learning Curve**: Dead simple API that you can master in seconds. No extensive documentation, complex configurations, or setup required - Log Engine works instantly.
21
+ - **Colorized Console Output**: Beautiful ANSI color-coded log levels with intelligent terminal formatting - instantly identify message severity at a glance with color-coded output.
22
+ - **Multiple Log Levels**: Support for DEBUG, INFO, WARN, ERROR, and SILENT levels with smart filtering - just set your level and let it handle the rest.
23
+ - **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.
24
+ - **Enhanced Formatting**: Structured log entries with dual timestamps (ISO + human-readable) and colored level indicators for maximum readability.
25
+ - **TypeScript Ready**: Full TypeScript support with comprehensive type definitions for a seamless development experience.
26
+ - **Zero Dependencies**: No external dependencies for maximum compatibility and security - keeps your bundle clean and your project simple.
27
+ - **Easy Integration**: Simple API that works seamlessly with existing Node.js applications. Just `import` and start logging - no middleware, plugins, or configuration required.
28
+
29
+ ## 🤔 How It Works
30
+ <!-- markdownlint-disable MD051 -->
31
+ 1. Log Engine automatically detects your environment using `NODE_ENV` and sets appropriate log levels for optimal performance
32
+ 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)
33
+ 3. Each log message is instantly formatted with precise timestamps in both ISO and human-readable formats
34
+ 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
35
+ 5. ANSI color codes ensure compatibility across different terminal environments while maintaining beautiful, readable output
36
+
37
+ Ready to streamline your application logging? Get started in seconds with our [simple installation](#đŸ“Ļ-installation)!
38
+ <!-- markdownlint-enable MD051 -->
39
+ ## 🤗 Special Thanks
40
+
41
+ <!-- markdownlint-disable MD033 -->
42
+ | <div align="center">💎 Platinum Sponsor</div> |
43
+ |:-------------------------------------------:|
44
+ | <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> |
45
+ | <div align="center"><a href="https://unthread.com" target="_blank"><b>Unthread</b></a><br/>Streamlined support ticketing for modern teams.</div> |
46
+ <!-- markdownlint-enable MD033 -->
47
+
48
+ ## 💸 Sponsored Ads
49
+
50
+ 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.
51
+
52
+ [![sponsored ads](https://gitads.dev/v1/ad-serve?source=wgtechlabs/log-engine@github)](https://gitads.dev/v1/ad-track?source=wgtechlabs/log-engine@github)
53
+
54
+ ## đŸ“Ļ Installation
55
+
56
+ Install the package using npm:
57
+
58
+ ```bash
20
59
  npm install @wgtechlabs/log-engine
21
60
  ```
22
61
 
23
- ## Usage
62
+ Or using yarn:
63
+
64
+ ```bash
65
+ yarn add @wgtechlabs/log-engine
66
+ ```
67
+
68
+ ## đŸ•šī¸ Usage
24
69
 
25
- Here's a quick example of how to use the Log Engine in your application:
70
+ ### Quick Start
26
71
 
27
72
  ```typescript
28
73
  import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
@@ -34,9 +79,7 @@ LogEngine.warn('This is a warning message');
34
79
  LogEngine.error('This is an error message');
35
80
  ```
36
81
 
37
- ### Configuration
38
-
39
- You can configure the logger based on your environment variables or specific requirements:
82
+ ### Custom Configuration
40
83
 
41
84
  ```typescript
42
85
  import { LogEngine, LogLevel } from '@wgtechlabs/log-engine';
@@ -52,16 +95,37 @@ if (env === 'production') {
52
95
  LogEngine.configure({ level: LogLevel.DEBUG });
53
96
  }
54
97
 
55
- // Now use the logger - only messages at or above the configured level will be shown
98
+ // Now use Log Engine - only messages at or above the configured level will be shown
56
99
  LogEngine.debug('This will only show in development');
57
100
  LogEngine.info('General information');
58
101
  LogEngine.warn('Warning message');
59
102
  LogEngine.error('Error message');
60
103
  ```
61
104
 
62
- ### Available Log Levels
105
+ ### Color-Coded Output 🎨
106
+
107
+ Log Engine now features beautiful, color-coded console output that makes debugging and monitoring a breeze:
108
+
109
+ ```typescript
110
+ import { LogEngine } from '@wgtechlabs/log-engine';
111
+
112
+ // Each log level gets its own distinct color for instant recognition
113
+ LogEngine.debug('🔍 Debugging user authentication flow'); // Purple/Magenta
114
+ LogEngine.info('â„šī¸ User successfully logged in'); // Blue
115
+ LogEngine.warn('âš ī¸ API rate limit at 80% capacity'); // Yellow
116
+ LogEngine.error('❌ Database connection timeout'); // Red
117
+ ```
118
+
119
+ **Why Colors Matter:**
63
120
 
64
- The logger supports the following levels (in order of severity):
121
+ - **Instant Recognition**: Quickly spot errors, warnings, and debug info without reading every line
122
+ - **Better Debugging**: Visually separate different types of messages during development
123
+ - **Production Monitoring**: Easily scan logs for critical issues in terminal environments
124
+ - **Enhanced Readability**: Color-coded timestamps and level indicators reduce eye strain
125
+
126
+ ### Log Levels
127
+
128
+ Log Engine supports the following levels (in order of severity):
65
129
 
66
130
  - `LogLevel.DEBUG` (0) - Detailed information for debugging
67
131
  - `LogLevel.INFO` (1) - General information
@@ -71,173 +135,100 @@ The logger supports the following levels (in order of severity):
71
135
 
72
136
  ### Auto-Configuration
73
137
 
74
- The logger automatically configures itself based on the `NODE_ENV` environment variable:
138
+ Log Engine automatically configures itself based on the `NODE_ENV` environment variable:
75
139
 
76
140
  - `production` → `LogLevel.WARN`
77
141
  - `development` → `LogLevel.DEBUG`
78
142
  - `test` → `LogLevel.ERROR`
79
143
  - `default` → `LogLevel.INFO`
80
144
 
81
- ## Log Format
145
+ ### Log Format
82
146
 
83
- The log messages will be formatted as follows:
147
+ Log messages are beautifully formatted with colorized timestamps, levels, and smart terminal output:
84
148
 
85
- ```
86
- [2025-05-20T16:57:45.678Z] [4:57 PM] [INFO] Message here.
149
+ ```bash
150
+ # Example colorized output (colors visible in terminal)
151
+ [2025-05-29T16:57:45.678Z][4:57 PM][DEBUG]: Debugging application flow
152
+ [2025-05-29T16:57:46.123Z][4:57 PM][INFO]: Server started successfully
153
+ [2025-05-29T16:57:47.456Z][4:57 PM][WARN]: API rate limit approaching
154
+ [2025-05-29T16:57:48.789Z][4:57 PM][ERROR]: Database connection failed
87
155
  ```
88
156
 
89
- ## Testing
157
+ **Color Scheme:**
90
158
 
91
- The log-engine project includes a comprehensive test suite to ensure reliability and functionality. The tests are organized into focused, maintainable files covering different aspects of the logging system.
159
+ - đŸŸŖ **DEBUG**: Magenta/Purple - Detailed debugging information
160
+ - đŸ”ĩ **INFO**: Blue - General informational messages
161
+ - 🟡 **WARN**: Yellow - Warning messages that need attention
162
+ - 🔴 **ERROR**: Red - Error messages requiring immediate action
163
+ - âšĢ **Timestamps**: Gray (ISO) and Cyan (local time) for easy scanning
92
164
 
93
- ### Test Structure
165
+ ## đŸ’Ŧ Community Discussions
94
166
 
95
- The test suite is organized as follows:
167
+ Join our community discussions to get help, share ideas, and connect with other users:
96
168
 
97
- ```
98
- src/__tests__/
99
- ├── test-utils.ts # Shared test utilities and mocking helpers
100
- ├── log-engine.test.ts # LogEngine core functionality tests
101
- ├── logger.test.ts # Logger class unit tests
102
- ├── formatter.test.ts # LogFormatter functionality tests
103
- ├── environment.test.ts # Environment-based configuration tests
104
- ├── log-level.test.ts # LogLevel enum validation tests
105
- └── integration.test.ts # End-to-end integration tests
106
- ```
169
+ - đŸ“Ŗ **[Announcements](https://github.com/wgtechlabs/log-engine/discussions/categories/announcements)**: Official updates from the maintainer
170
+ - 📸 **[Showcase](https://github.com/wgtechlabs/log-engine/discussions/categories/showcase)**: Show and tell your implementation
171
+ - 💖 **[Wall of Love](https://github.com/wgtechlabs/log-engine/discussions/categories/wall-of-love)**: Share your experience with the library
172
+ - 🛟 **[Help & Support](https://github.com/wgtechlabs/log-engine/discussions/categories/help-support)**: Get assistance from the community
173
+ - 🧠 **[Ideas](https://github.com/wgtechlabs/log-engine/discussions/categories/ideas)**: Suggest new features and improvements
107
174
 
108
- ### Running Tests
175
+ ## 🛟 Help & Support
109
176
 
110
- #### Run All Tests
111
- ```bash
112
- npm test
113
- ```
177
+ ### Getting Help
114
178
 
115
- #### Run Tests with Coverage
116
- ```bash
117
- npm run test:coverage
118
- ```
179
+ Need assistance with the library? Here's how to get help:
180
+ <!-- markdownlint-disable MD051 -->
181
+ - **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.
182
+ - **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.
183
+ - **Documentation**: Review the [usage instructions](#đŸ•šī¸-usage) in this README for common examples and configurations.
184
+ - **Known Issues**: Browse [existing issues](https://github.com/wgtechlabs/log-engine/issues) to see if your problem has already been reported.
185
+ <!-- markdownlint-enable MD051 -->
119
186
 
120
- #### Run Tests in Watch Mode
121
- ```bash
122
- npm run test:watch
123
- ```
187
+ ### Reporting Issues
124
188
 
125
- #### Run Specific Test Files
126
- ```bash
127
- # Run only LogEngine tests
128
- npm test log-engine
129
-
130
- # Run only Logger class tests
131
- npm test logger
132
-
133
- # Run only integration tests
134
- npm test integration
189
+ 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.
135
190
 
136
- # Run only formatter tests
137
- npm test formatter
138
- ```
191
+ ### Security Vulnerabilities
139
192
 
140
- ### Test Coverage
193
+ For security vulnerabilities, please do not report them publicly. Follow the guidelines in our [security policy](./security.md) to responsibly disclose security issues.
141
194
 
142
- The project maintains high test coverage:
195
+ Your contributions to improving this project are greatly appreciated! 🙏✨
143
196
 
144
- - **Statements**: ~94%
145
- - **Branches**: ~87%
146
- - **Functions**: ~90%
147
- - **Lines**: ~94%
197
+ ## đŸŽ¯ Contributing
148
198
 
149
- Coverage reports are generated in the `coverage/` directory after running `npm run test:coverage`.
199
+ 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!
150
200
 
151
- ### Test Categories
201
+ Read the project's [contributing guide](./CONTRIBUTING.md) for more info, including testing guidelines and requirements.
152
202
 
153
- #### Unit Tests
154
- - **LogEngine** (`log-engine.test.ts`): Core logging functionality, configuration, and level filtering
155
- - **Logger** (`logger.test.ts`): Logger class behavior and configuration
156
- - **LogFormatter** (`formatter.test.ts`): Message formatting with timestamps and levels
157
- - **LogLevel** (`log-level.test.ts`): Enum values and ordering validation
203
+ ## 🙏 Sponsor
158
204
 
159
- #### Configuration Tests
160
- - **Environment** (`environment.test.ts`): Auto-configuration based on `NODE_ENV`
205
+ Like this project? **Leave a star**! ⭐⭐⭐⭐⭐
161
206
 
162
- #### Integration Tests
163
- - **Integration** (`integration.test.ts`): End-to-end scenarios and workflows
207
+ There are several ways you can support this project:
164
208
 
165
- ### Writing Tests
209
+ - [Become a sponsor](https://github.com/sponsors/wgtechlabs) and get some perks! 💖
210
+ - [Buy me a coffee](https://buymeacoffee.com/wgtechlabs) if you just love what I do! ☕
166
211
 
167
- When contributing to the project, follow these testing guidelines:
212
+ ## ⭐ GitHub Star Nomination
168
213
 
169
- #### Test Structure
170
- ```typescript
171
- import { LogEngine, LogLevel } from '../index';
172
- import { setupConsoleMocks, restoreConsoleMocks, ConsoleMocks } from './test-utils';
173
-
174
- describe('Feature Name', () => {
175
- let mocks: ConsoleMocks;
176
-
177
- beforeEach(() => {
178
- mocks = setupConsoleMocks();
179
- // Setup test state
180
- });
181
-
182
- afterEach(() => {
183
- restoreConsoleMocks(mocks);
184
- // Cleanup
185
- });
186
-
187
- it('should describe the expected behavior', () => {
188
- // Arrange
189
- LogEngine.configure({ level: LogLevel.INFO });
190
-
191
- // Act
192
- LogEngine.info('Test message');
193
-
194
- // Assert
195
- expect(mocks.mockConsoleLog).toHaveBeenCalledWith(
196
- expect.stringContaining('[INFO] Test message')
197
- );
198
- });
199
- });
200
- ```
214
+ 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!
201
215
 
202
- #### Best Practices
203
- - Use descriptive test names that explain the expected behavior
204
- - Follow the Arrange-Act-Assert pattern
205
- - Use the shared `test-utils` for console mocking
206
- - Clean up after each test to avoid side effects
207
- - Test both positive and negative scenarios
208
- - Include edge cases and error conditions
216
+ ## 📋 Code of Conduct
209
217
 
210
- #### Console Mocking
211
- The project uses shared console mocking utilities:
218
+ 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.
212
219
 
213
- ```typescript
214
- import { setupConsoleMocks, restoreConsoleMocks, ConsoleMocks } from './test-utils';
215
-
216
- // In your test setup
217
- const mocks = setupConsoleMocks();
218
-
219
- // In your test cleanup
220
- restoreConsoleMocks(mocks);
221
-
222
- // In your assertions
223
- expect(mocks.mockConsoleLog).toHaveBeenCalledWith(expected);
224
- expect(mocks.mockConsoleWarn).toHaveBeenCalledTimes(1);
225
- expect(mocks.mockConsoleError).not.toHaveBeenCalled();
226
- ```
220
+ ## 📃 License
227
221
 
228
- ### Continuous Integration
222
+ This project is licensed under the [GNU Affero General Public License v3.0](https://opensource.org/licenses/AGPL-3.0). This license requires that all modifications to the code must be shared under the same license, especially when the software is used over a network. See the [LICENSE](LICENSE) file for the full license text.
229
223
 
230
- Tests are automatically run on:
231
- - Pull requests
232
- - Pushes to main branch
233
- - Release workflows
224
+ ## 📝 Author
234
225
 
235
- Ensure all tests pass before submitting contributions.
226
+ 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).
236
227
 
237
- ## Contributing
228
+ [![contributors](https://contrib.rocks/image?repo=wgtechlabs/log-engine)](https://github.com/wgtechlabs/log-engine/graphs/contributors)
238
229
 
239
- Contributions are welcome! Please feel free to submit a pull request or open an issue for any enhancements or bugs.
230
+ ---
240
231
 
241
- ## License
232
+ đŸ’ģ 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) 🙏
242
233
 
243
- This project is licensed under the AGPL-v3. See the LICENSE file for more details.
234
+ <!-- GitAds-Verify: O4MESJK7VTBCELWNTFQAWB5HDX57H9MS -->
package/dist/formatter.js CHANGED
@@ -1,8 +1,23 @@
1
1
  "use strict";
2
+ /**
3
+ * Log message formatter that provides colorized console output with timestamps
4
+ * Handles ANSI color codes and structured log message formatting
5
+ */
2
6
  Object.defineProperty(exports, "__esModule", { value: true });
3
7
  exports.LogFormatter = void 0;
4
8
  const types_1 = require("./types");
9
+ /**
10
+ * LogFormatter class responsible for formatting log messages with colors and timestamps
11
+ * Creates readable, colored console output with ISO timestamps and local time
12
+ */
5
13
  class LogFormatter {
14
+ /**
15
+ * Formats a log message with timestamp, level indicator, and appropriate coloring
16
+ * Creates a structured log entry: [ISO_TIMESTAMP][LOCAL_TIME][LEVEL]: message
17
+ * @param level - The log level to format for
18
+ * @param message - The message content to format
19
+ * @returns Formatted string with ANSI colors and timestamps
20
+ */
6
21
  static format(level, message) {
7
22
  const now = new Date();
8
23
  const isoTimestamp = now.toISOString();
@@ -12,8 +27,18 @@ class LogFormatter {
12
27
  hour12: true
13
28
  });
14
29
  const levelName = this.getLevelName(level);
15
- return `[${isoTimestamp}] [${timeString}] [${levelName}] ${message}`;
30
+ const levelColor = this.getLevelColor(level);
31
+ // Apply colors to each component for better readability
32
+ const coloredTimestamp = `${this.colors.gray}[${isoTimestamp}]${this.colors.reset}`;
33
+ const coloredTimeString = `${this.colors.cyan}[${timeString}]${this.colors.reset}`;
34
+ const coloredLevel = `${levelColor}[${levelName}]${this.colors.reset}`;
35
+ return `${coloredTimestamp}${coloredTimeString}${coloredLevel}: ${message}`;
16
36
  }
37
+ /**
38
+ * Converts LogLevel enum to human-readable string
39
+ * @param level - The LogLevel to convert
40
+ * @returns String representation of the log level
41
+ */
17
42
  static getLevelName(level) {
18
43
  switch (level) {
19
44
  case types_1.LogLevel.DEBUG: return 'DEBUG';
@@ -24,5 +49,33 @@ class LogFormatter {
24
49
  default: return 'UNKNOWN';
25
50
  }
26
51
  }
52
+ /**
53
+ * Maps LogLevel to appropriate ANSI color code
54
+ * Colors help quickly identify message severity in console output
55
+ * @param level - The LogLevel to get color for
56
+ * @returns ANSI color escape sequence
57
+ */
58
+ static getLevelColor(level) {
59
+ switch (level) {
60
+ case types_1.LogLevel.DEBUG: return this.colors.magenta; // Purple for debug info
61
+ case types_1.LogLevel.INFO: return this.colors.blue; // Blue for general info
62
+ case types_1.LogLevel.WARN: return this.colors.yellow; // Yellow for warnings
63
+ case types_1.LogLevel.ERROR: return this.colors.red; // Red for errors
64
+ case types_1.LogLevel.SILENT: return this.colors.dim; // Dim for silent (shouldn't be used)
65
+ default: return this.colors.white; // White for unknown levels
66
+ }
67
+ }
27
68
  }
28
69
  exports.LogFormatter = LogFormatter;
70
+ // ANSI color codes for terminal output styling
71
+ LogFormatter.colors = {
72
+ reset: '\x1b[0m', // Reset all formatting
73
+ dim: '\x1b[2m', // Dim/faded text
74
+ red: '\x1b[31m', // Red text (errors)
75
+ yellow: '\x1b[33m', // Yellow text (warnings)
76
+ blue: '\x1b[34m', // Blue text (info)
77
+ magenta: '\x1b[35m', // Magenta text (debug)
78
+ cyan: '\x1b[36m', // Cyan text (timestamps)
79
+ white: '\x1b[37m', // White text (default)
80
+ gray: '\x1b[90m' // Gray text (timestamps)
81
+ };
package/dist/index.js CHANGED
@@ -1,10 +1,22 @@
1
1
  "use strict";
2
+ /**
3
+ * Main entry point for the Log Engine library
4
+ * Provides a simple, configurable logging interface with environment-based auto-configuration
5
+ */
2
6
  Object.defineProperty(exports, "__esModule", { value: true });
3
7
  exports.LogLevel = exports.LogEngine = void 0;
4
8
  const logger_1 = require("./logger");
5
9
  const types_1 = require("./types");
10
+ // Create singleton logger instance
6
11
  const logger = new logger_1.Logger();
7
- // Auto-configure based on NODE_ENV if available
12
+ /**
13
+ * Determines the appropriate default log level based on NODE_ENV
14
+ * - production: WARN (reduce noise in production)
15
+ * - development: DEBUG (verbose logging for development)
16
+ * - test: ERROR (minimal logging during tests)
17
+ * - default: INFO (balanced logging for other environments)
18
+ * @returns The appropriate LogLevel for the current environment
19
+ */
8
20
  const getDefaultLogLevel = () => {
9
21
  const nodeEnv = process.env.NODE_ENV;
10
22
  switch (nodeEnv) {
@@ -18,12 +30,70 @@ const getDefaultLogLevel = () => {
18
30
  return types_1.LogLevel.INFO;
19
31
  }
20
32
  };
33
+ // Initialize logger with environment-appropriate default level
21
34
  logger.configure({ level: getDefaultLogLevel() });
35
+ /**
36
+ * Main LogEngine API - provides all logging functionality with a clean interface
37
+ * Auto-configured based on NODE_ENV, but can be reconfigured at runtime
38
+ */
22
39
  exports.LogEngine = {
40
+ /**
41
+ * Configure the logger with custom settings
42
+ * @param config - Partial configuration object containing level and/or environment
43
+ * @example
44
+ * ```typescript
45
+ * LogEngine.configure({ level: LogLevel.DEBUG });
46
+ * LogEngine.configure({ level: LogLevel.WARN, environment: 'staging' });
47
+ * ```
48
+ */
23
49
  configure: (config) => logger.configure(config),
50
+ /**
51
+ * Log a debug message (lowest priority)
52
+ * Only shown when log level is DEBUG or lower
53
+ * Useful for detailed diagnostic information during development
54
+ * @param message - The debug message to log
55
+ * @example
56
+ * ```typescript
57
+ * LogEngine.debug('User authentication flow started');
58
+ * LogEngine.debug(`Processing ${items.length} items`);
59
+ * ```
60
+ */
24
61
  debug: (message) => logger.debug(message),
62
+ /**
63
+ * Log an informational message
64
+ * General information about application flow and state
65
+ * Shown when log level is INFO or lower
66
+ * @param message - The info message to log
67
+ * @example
68
+ * ```typescript
69
+ * LogEngine.info('Application started successfully');
70
+ * LogEngine.info('User logged in: john@example.com');
71
+ * ```
72
+ */
25
73
  info: (message) => logger.info(message),
74
+ /**
75
+ * Log a warning message
76
+ * Indicates potential issues that don't prevent operation
77
+ * Shown when log level is WARN or lower
78
+ * @param message - The warning message to log
79
+ * @example
80
+ * ```typescript
81
+ * LogEngine.warn('API rate limit approaching');
82
+ * LogEngine.warn('Deprecated function called');
83
+ * ```
84
+ */
26
85
  warn: (message) => logger.warn(message),
86
+ /**
87
+ * Log an error message (highest priority)
88
+ * Indicates serious problems that need attention
89
+ * Always shown unless log level is SILENT
90
+ * @param message - The error message to log
91
+ * @example
92
+ * ```typescript
93
+ * LogEngine.error('Database connection failed');
94
+ * LogEngine.error('Authentication token expired');
95
+ * ```
96
+ */
27
97
  error: (message) => logger.error(message)
28
98
  };
29
99
  var types_2 = require("./types");
package/dist/logger.js CHANGED
@@ -1,38 +1,79 @@
1
1
  "use strict";
2
+ /**
3
+ * Core Logger class that handles log message output with configurable levels
4
+ * Supports DEBUG, INFO, WARN, ERROR levels with intelligent filtering
5
+ * Uses colorized console output with timestamps for better readability
6
+ */
2
7
  Object.defineProperty(exports, "__esModule", { value: true });
3
8
  exports.Logger = void 0;
4
9
  const types_1 = require("./types");
5
10
  const formatter_1 = require("./formatter");
11
+ /**
12
+ * Logger class responsible for managing log output and configuration
13
+ * Provides level-based filtering and formatted console output
14
+ */
6
15
  class Logger {
7
16
  constructor() {
17
+ // Internal configuration state with sensible defaults
8
18
  this.config = {
9
19
  level: types_1.LogLevel.INFO
10
20
  };
11
21
  }
22
+ /**
23
+ * Updates logger configuration with new settings
24
+ * Merges provided config with existing settings (partial update)
25
+ * @param config - Partial configuration object to apply
26
+ */
12
27
  configure(config) {
13
28
  this.config = { ...this.config, ...config };
14
29
  }
30
+ /**
31
+ * Determines if a message should be logged based on current log level
32
+ * Messages are shown only if their level >= configured minimum level
33
+ * @param level - The log level of the message to check
34
+ * @returns true if message should be logged, false otherwise
35
+ */
15
36
  shouldLog(level) {
16
37
  return level >= this.config.level;
17
38
  }
39
+ /**
40
+ * Log a debug message with DEBUG level formatting
41
+ * Uses console.log for output with purple/magenta coloring
42
+ * @param message - The debug message to log
43
+ */
18
44
  debug(message) {
19
45
  if (this.shouldLog(types_1.LogLevel.DEBUG)) {
20
46
  const formatted = formatter_1.LogFormatter.format(types_1.LogLevel.DEBUG, message);
21
47
  console.log(formatted);
22
48
  }
23
49
  }
50
+ /**
51
+ * Log an informational message with INFO level formatting
52
+ * Uses console.log for output with blue coloring
53
+ * @param message - The info message to log
54
+ */
24
55
  info(message) {
25
56
  if (this.shouldLog(types_1.LogLevel.INFO)) {
26
57
  const formatted = formatter_1.LogFormatter.format(types_1.LogLevel.INFO, message);
27
58
  console.log(formatted);
28
59
  }
29
60
  }
61
+ /**
62
+ * Log a warning message with WARN level formatting
63
+ * Uses console.warn for output with yellow coloring
64
+ * @param message - The warning message to log
65
+ */
30
66
  warn(message) {
31
67
  if (this.shouldLog(types_1.LogLevel.WARN)) {
32
68
  const formatted = formatter_1.LogFormatter.format(types_1.LogLevel.WARN, message);
33
69
  console.warn(formatted);
34
70
  }
35
71
  }
72
+ /**
73
+ * Log an error message with ERROR level formatting
74
+ * Uses console.error for output with red coloring
75
+ * @param message - The error message to log
76
+ */
36
77
  error(message) {
37
78
  if (this.shouldLog(types_1.LogLevel.ERROR)) {
38
79
  const formatted = formatter_1.LogFormatter.format(types_1.LogLevel.ERROR, message);
@@ -1,11 +1,25 @@
1
1
  "use strict";
2
+ /**
3
+ * Type definitions for the Log Engine library
4
+ * Provides strongly-typed interfaces for configuration and log levels
5
+ */
2
6
  Object.defineProperty(exports, "__esModule", { value: true });
3
7
  exports.LogLevel = void 0;
8
+ /**
9
+ * Log levels in order of priority (lowest to highest)
10
+ * Higher numeric values represent higher priority levels
11
+ * When a level is set, only messages at that level or higher are shown
12
+ */
4
13
  var LogLevel;
5
14
  (function (LogLevel) {
15
+ /** Detailed diagnostic information, typically only of interest during development */
6
16
  LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
17
+ /** General information about application flow and state */
7
18
  LogLevel[LogLevel["INFO"] = 1] = "INFO";
19
+ /** Potentially harmful situations that don't prevent operation */
8
20
  LogLevel[LogLevel["WARN"] = 2] = "WARN";
21
+ /** Error events that might still allow the application to continue */
9
22
  LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
23
+ /** Completely disable all logging output */
10
24
  LogLevel[LogLevel["SILENT"] = 4] = "SILENT";
11
25
  })(LogLevel || (exports.LogLevel = LogLevel = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wgtechlabs/log-engine",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "A lightweight and efficient logging utility designed specifically for bot applications running on Node.js.",
5
5
  "keywords": [
6
6
  "logging",