traceperf 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +230 -263
  2. package/dist/browser.d.ts +52 -7
  3. package/dist/browser.js +198 -35
  4. package/dist/browser.js.map +1 -1
  5. package/dist/core/index.d.ts +1 -0
  6. package/dist/core/index.js +1 -0
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/core/optimized-performance-monitor.d.ts +227 -0
  9. package/dist/core/optimized-performance-monitor.js +543 -0
  10. package/dist/core/optimized-performance-monitor.js.map +1 -0
  11. package/dist/esm/browser.d.ts +52 -7
  12. package/dist/esm/browser.js +196 -34
  13. package/dist/esm/browser.js.map +1 -1
  14. package/dist/esm/core/index.d.ts +1 -0
  15. package/dist/esm/core/index.js +1 -0
  16. package/dist/esm/core/index.js.map +1 -1
  17. package/dist/esm/core/optimized-performance-monitor.d.ts +227 -0
  18. package/dist/esm/core/optimized-performance-monitor.js +535 -0
  19. package/dist/esm/core/optimized-performance-monitor.js.map +1 -0
  20. package/dist/esm/index.d.ts +7 -8
  21. package/dist/esm/index.js +18 -19
  22. package/dist/esm/index.js.map +1 -1
  23. package/dist/esm/trackers/execution.d.ts +34 -26
  24. package/dist/esm/trackers/execution.js +99 -60
  25. package/dist/esm/trackers/execution.js.map +1 -1
  26. package/dist/esm/trackers/performance.d.ts +7 -21
  27. package/dist/esm/trackers/performance.js +25 -19
  28. package/dist/esm/trackers/performance.js.map +1 -1
  29. package/dist/esm/types/config.d.ts +16 -2
  30. package/dist/esm/types/index.d.ts +32 -34
  31. package/dist/esm/types/logger.d.ts +11 -2
  32. package/dist/esm/utils/colors.js +12 -0
  33. package/dist/esm/utils/colors.js.map +1 -1
  34. package/dist/esm/utils/string.d.ts +29 -0
  35. package/dist/esm/utils/string.js +45 -0
  36. package/dist/esm/utils/string.js.map +1 -0
  37. package/dist/index.d.ts +7 -8
  38. package/dist/index.js +42 -20
  39. package/dist/index.js.map +1 -1
  40. package/dist/trackers/execution.d.ts +34 -26
  41. package/dist/trackers/execution.js +98 -59
  42. package/dist/trackers/execution.js.map +1 -1
  43. package/dist/trackers/performance.d.ts +7 -21
  44. package/dist/trackers/performance.js +25 -19
  45. package/dist/trackers/performance.js.map +1 -1
  46. package/dist/types/config.d.ts +16 -2
  47. package/dist/types/index.d.ts +32 -34
  48. package/dist/types/logger.d.ts +11 -2
  49. package/dist/types.d.ts +65 -0
  50. package/dist/types.js +6 -0
  51. package/dist/types.js.map +1 -0
  52. package/dist/utils/colors.js +12 -0
  53. package/dist/utils/colors.js.map +1 -1
  54. package/dist/utils/string.d.ts +29 -0
  55. package/dist/utils/string.js +50 -0
  56. package/dist/utils/string.js.map +1 -0
  57. package/package.json +11 -8
package/README.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # TracePerf
2
2
 
3
- Advanced console logging & performance tracking for Node.js applications.
3
+ Advanced performance tracking and execution monitoring for Node.js applications.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/traceperf.svg)](https://www.npmjs.com/package/traceperf)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
8
  ## Features
9
9
 
10
- - **Structured and Visually Appealing Logs**: A better alternative to `console.log()` with colors, icons, and formatting.
11
- - **Execution Flow Tracing**: Track function calls and visualize the execution flow with ASCII art.
12
- - **Nested Function Tracking**: Multiple approaches to track nested function calls with detailed visualization.
13
- - **Performance Bottleneck Detection**: Identify slow functions and get suggestions for optimization.
14
- - **Conditional Logging Modes**: Different logging levels for development, staging, and production.
15
- - **Nested Logging**: Group related logs with indentation for better readability.
16
- - **Auto-Remove Debug Logs**: Automatically filter out debug logs in production.
17
- - **Universal Module Compatibility**: Works with both CommonJS and ESM environments.
10
+ - **High-Performance Execution Monitoring**: Track function execution time with minimal overhead
11
+ - **Memory Usage Tracking**: Monitor memory consumption of your functions and identify memory leaks
12
+ - **Flexible Tracking Modes**: Choose between performance, balanced, and detailed tracking based on your needs
13
+ - **Execution Flow Visualization**: Visualize execution flows with intelligent formatting
14
+ - **Nested Function Tracking**: Track function calls within other functions to understand complex flows
15
+ - **Customizable Threshold Detection**: Focus on functions that exceed specific execution time thresholds
16
+ - **Sampling Control**: Adjust sampling rates to minimize performance impact in production
17
+ - **Universal Module Compatibility**: Works with both CommonJS and ESM environments
18
18
 
19
19
  ## Installation
20
20
 
@@ -22,333 +22,300 @@ Advanced console logging & performance tracking for Node.js applications.
22
22
  npm install traceperf
23
23
  ```
24
24
 
25
- ## Basic Usage
26
-
27
- ### CommonJS (Node.js)
25
+ ## Quick Start
28
26
 
29
27
  ```javascript
30
- const tracePerf = require('traceperf');
31
-
32
- // Basic logging
33
- tracePerf.info('This is an info message');
34
- tracePerf.warn('This is a warning message');
35
- tracePerf.error('This is an error message');
36
- tracePerf.debug('This is a debug message');
37
-
38
- // Logging with objects
39
- tracePerf.info('User data:', { id: 1, name: 'John Doe' });
40
-
41
- // Nested logging with groups
42
- tracePerf.group('User Authentication');
43
- tracePerf.info('Checking credentials');
44
- tracePerf.warn('Invalid password attempt');
45
- tracePerf.groupEnd();
28
+ const traceperf = require('traceperf');
29
+
30
+ // Track a synchronous function
31
+ const result = traceperf.track(() => {
32
+ // Your code here
33
+ return 'result';
34
+ }, { label: 'myFunction' });
35
+
36
+ // Track an asynchronous function
37
+ async function main() {
38
+ const result = await traceperf.track(async () => {
39
+ // Your async code here
40
+ return 'async result';
41
+ }, { label: 'asyncFunction' });
42
+ }
46
43
  ```
47
44
 
48
- ### ESM (ECMAScript Modules)
45
+ ## Tracking Modes
46
+
47
+ TracePerf provides different tracking modes to balance performance with detail:
49
48
 
50
49
  ```javascript
51
- import tracePerf from 'traceperf';
50
+ const { TrackingMode, createTracePerf } = require('traceperf');
51
+
52
+ // Create a custom instance with performance-focused tracking
53
+ const performanceTracker = createTracePerf({
54
+ trackingMode: TrackingMode.PERFORMANCE,
55
+ silent: true,
56
+ threshold: 100, // only track functions that take more than 100ms
57
+ sampleRate: 0.1 // only track 10% of function calls
58
+ });
52
59
 
53
- // Use the same API as with CommonJS
54
- tracePerf.info('This is an info message');
60
+ // Create a custom instance with detailed tracking for development
61
+ const devTracker = createTracePerf({
62
+ trackingMode: TrackingMode.DETAILED,
63
+ trackMemory: true,
64
+ enableNestedTracking: true
65
+ });
55
66
  ```
56
67
 
57
- ## Execution Flow Tracking
68
+ ## Tracking Individual Functions
58
69
 
59
70
  ```javascript
60
- function fetchData() {
61
- processData();
62
- }
63
-
64
- function processData() {
65
- calculateResults();
66
- }
67
-
68
- function calculateResults() {
69
- return 'done';
70
- }
71
-
72
- // Track the execution of the fetchData function
73
- const result = tracePerf.track(fetchData);
74
- ```
71
+ // Track a single function execution
72
+ const result = traceperf.track(() => {
73
+ // Function body
74
+ return someValue;
75
+ }, {
76
+ label: 'functionName',
77
+ threshold: 50, // ms
78
+ trackMemory: true
79
+ });
75
80
 
76
- Output:
81
+ // Create a trackable version of an existing function
82
+ const myFunction = (a, b) => a + b;
83
+ const trackedFunction = traceperf.createTrackable(myFunction, {
84
+ label: 'addition'
85
+ });
77
86
 
78
- ```
79
- Execution Flow:
80
- ┌──────────────────────────────┐
81
- │ fetchData │ ⏱ 200ms
82
- └──────────────────────────────┘
83
- │
84
- ▼
85
- ┌──────────────────────────────┐
86
- │ processData │ ⏱ 500ms ⚠️ SLOW
87
- └──────────────────────────────┘
88
- │
89
- ▼
90
- ┌──────────────────────────────┐
91
- │ calculateResults │ ⏱ 300ms
92
- └──────────────────────────────┘
87
+ // Now use it normally
88
+ const sum = trackedFunction(5, 3); // will be tracked
93
89
  ```
94
90
 
95
- ## Conditional Logging Modes
91
+ ## Tracking Methods in a Module
96
92
 
97
93
  ```javascript
98
- // Development mode (default)
99
- tracePerf.setMode('dev');
100
- tracePerf.debug('Debug message'); // Shown
101
- tracePerf.info('Info message'); // Shown
102
- tracePerf.warn('Warning message'); // Shown
103
- tracePerf.error('Error message'); // Shown
104
-
105
- // Staging mode
106
- tracePerf.setMode('staging');
107
- tracePerf.debug('Debug message'); // Not shown
108
- tracePerf.info('Info message'); // Not shown
109
- tracePerf.warn('Warning message'); // Shown
110
- tracePerf.error('Error message'); // Shown
111
-
112
- // Production mode
113
- tracePerf.setMode('prod');
114
- tracePerf.debug('Debug message'); // Not shown
115
- tracePerf.info('Info message'); // Not shown
116
- tracePerf.warn('Warning message'); // Not shown
117
- tracePerf.error('Error message'); // Shown
118
- ```
94
+ const userService = {
95
+ getUser: async (id) => { /* implementation */ },
96
+ updateUser: async (id, data) => { /* implementation */ },
97
+ deleteUser: async (id) => { /* implementation */ }
98
+ };
119
99
 
120
- ## Browser Usage (React, Next.js, etc.)
100
+ // Register all methods for tracking
101
+ const trackedUserService = traceperf.registerModule(userService);
121
102
 
122
- TracePerf also provides a browser-compatible version for use in frontend applications:
103
+ // Now all method calls will be tracked
104
+ const user = await trackedUserService.getUser(123);
105
+ ```
123
106
 
124
- ### ESM (Modern Browsers)
107
+ ## Advanced Configuration
125
108
 
126
109
  ```javascript
127
- // Import the browser version
128
- import tracePerf from 'traceperf/browser';
110
+ const { createTracePerf, TrackingMode } = require('traceperf');
129
111
 
130
- // Use it just like the Node.js version
131
- tracePerf.info('This works in the browser!');
112
+ const customTracker = createTracePerf({
113
+ // Tracking mode affects detail level and performance impact
114
+ trackingMode: TrackingMode.BALANCED,
115
+
116
+ // Enable or disable performance statistics in console
117
+ silent: false,
118
+
119
+ // Track memory usage (slight performance impact)
120
+ trackMemory: true,
121
+
122
+ // Enable tracking of nested function calls
123
+ enableNestedTracking: true,
124
+
125
+ // Minimum execution time to track (milliseconds)
126
+ threshold: 50,
127
+
128
+ // Percentage of function calls to track (0.0 to 1.0)
129
+ sampleRate: 1.0
130
+ });
132
131
  ```
133
132
 
134
- ### CommonJS (Bundlers with CommonJS support)
133
+ ## Browser Support
134
+
135
+ TracePerf includes a browser-compatible version:
135
136
 
136
137
  ```javascript
137
- // Import the browser version with require
138
- const tracePerf = require('traceperf/browser');
138
+ import traceperf from 'traceperf/browser';
139
139
 
140
- // Use it just like the Node.js version
141
- tracePerf.info('This works in the browser with CommonJS bundlers!');
140
+ // Use the same API as in Node.js
141
+ traceperf.track(() => {
142
+ // Your code
143
+ });
142
144
  ```
143
145
 
144
- ### Browser Example
146
+ ## Examples
145
147
 
146
- ```javascript
147
- // Import using your preferred method
148
- import tracePerf from 'traceperf/browser';
148
+ TracePerf includes several example files to help you get started:
149
149
 
150
- // Track function performance
151
- function expensiveCalculation() {
152
- // ...complex logic
153
- return result;
154
- }
150
+ - **`examples/optimized-tracking-example.js`**: Demonstrates various ways to use the optimized tracking implementation
151
+ - **`examples/browser-example.js`**: Shows how to use TracePerf in browser environments
155
152
 
156
- const result = tracePerf.track(expensiveCalculation);
157
- ```
153
+ ### Tracking an Async Function
158
154
 
159
- ### React Component Example
160
-
161
- ```jsx
162
- import React, { useEffect } from 'react';
163
- import tracePerf from 'traceperf/browser';
164
-
165
- function DataComponent() {
166
- useEffect(() => {
167
- tracePerf.group('Component Lifecycle');
168
- tracePerf.info('Component mounted');
169
-
170
- // Fetch data with performance tracking
171
- tracePerf.track(async () => {
172
- const data = await fetchData();
173
- // Process data...
174
- }, { label: 'fetchAndProcessData', threshold: 300 });
175
-
176
- return () => {
177
- tracePerf.info('Component unmounting');
178
- tracePerf.groupEnd();
179
- };
180
- }, []);
181
-
182
- // Component rendering...
155
+ ```javascript
156
+ const { createTracePerf } = require('traceperf');
157
+ const traceperf = createTracePerf();
158
+
159
+ async function fetchData(url) {
160
+ return traceperf.track(async () => {
161
+ const response = await fetch(url);
162
+ return response.json();
163
+ }, {
164
+ label: 'fetchData',
165
+ trackMemory: true
166
+ });
183
167
  }
184
168
  ```
185
169
 
186
- ## Advanced Configuration
170
+ ### Tracking Nested Functions
187
171
 
188
172
  ```javascript
189
- const { createLogger } = require('traceperf');
190
-
191
- // Create a custom logger instance
192
- const logger = createLogger({
193
- mode: 'dev',
194
- level: 'debug',
195
- colorize: true,
196
- timestamp: true,
197
- performanceThreshold: 100, // ms
198
- indentSize: 2,
199
- });
200
-
201
- // Use the custom logger
202
- logger.info('Custom logger');
203
- ```
204
-
205
- ## API Reference
206
-
207
- ### Logging Methods
173
+ const { createTracePerf } = require('traceperf');
174
+ const traceperf = createTracePerf({ enableNestedTracking: true });
175
+
176
+ async function processData() {
177
+ return await traceperf.track(async () => {
178
+ // This function call will be automatically tracked as a child
179
+ const data = await fetchData();
180
+ return transformData(data);
181
+ }, {
182
+ label: 'processData'
183
+ });
184
+ }
208
185
 
209
- - `info(message, ...args)`: Log an informational message
210
- - `warn(message, ...args)`: Log a warning message
211
- - `error(message, ...args)`: Log an error message
212
- - `debug(message, ...args)`: Log a debug message (filtered in production)
186
+ async function fetchData() {
187
+ return await traceperf.track(async () => {
188
+ // Implementation
189
+ }, { label: 'fetchData' });
190
+ }
213
191
 
214
- ### Grouping
192
+ function transformData(data) {
193
+ return traceperf.track(() => {
194
+ // Implementation
195
+ }, { label: 'transformData' });
196
+ }
197
+ ```
215
198
 
216
- - `group(label)`: Start a new log group with the given label
217
- - `groupEnd()`: End the current log group
199
+ ### Optimizing for Production
218
200
 
219
- ### Execution Tracking
201
+ ```javascript
202
+ const { createTracePerf, TrackingMode } = require('traceperf');
203
+
204
+ // Development environment
205
+ const devTracker = createTracePerf({
206
+ trackingMode: TrackingMode.DETAILED,
207
+ silent: false,
208
+ trackMemory: true,
209
+ threshold: 0 // track everything
210
+ });
220
211
 
221
- - `track(fn, options)`: Track the execution of a function and log performance metrics
222
- - `options.label`: Custom label for the tracked function
223
- - `options.threshold`: Performance threshold in milliseconds
224
- - `options.includeMemory`: Whether to include memory usage tracking
225
- - `options.silent`: Whether to suppress logging for this tracking
212
+ // Production environment
213
+ const prodTracker = createTracePerf({
214
+ trackingMode: TrackingMode.PERFORMANCE,
215
+ silent: true, // don't log to console
216
+ trackMemory: false, // minimize overhead
217
+ threshold: 100, // only track slow functions
218
+ sampleRate: 0.01 // track only 1% of function calls
219
+ });
226
220
 
227
- ### Configuration
221
+ // Use based on environment
222
+ const traceperf = process.env.NODE_ENV === 'production' ? prodTracker : devTracker;
223
+ ```
228
224
 
229
- - `setMode(mode)`: Set the operational mode ('dev', 'staging', 'prod')
230
- - `getMode()`: Get the current operational mode
225
+ ## Browser Usage
231
226
 
232
- ## License
227
+ To use TracePerf in the browser:
233
228
 
234
- MIT
229
+ ```html
230
+ <script src="dist/traceperf.browser.js"></script>
231
+ <script>
232
+ const { createTracePerf, TrackingMode } = TracePerf;
233
+
234
+ const browserTracker = createTracePerf({
235
+ trackingMode: TrackingMode.BALANCED,
236
+ trackMemory: true
237
+ });
238
+
239
+ // Now use it to track your functions
240
+ browserTracker.track(() => {
241
+ // DOM operations or other browser-side logic
242
+ }, { label: 'domOperation' });
243
+ </script>
244
+ ```
235
245
 
236
- ## Advanced Usage
246
+ Or with ES modules:
237
247
 
238
- ### Tracking Nested Function Calls
248
+ ```javascript
249
+ import { createTracePerf, TrackingMode } from 'traceperf/browser';
239
250
 
240
- TracePerf provides two approaches for tracking nested function calls, allowing you to visualize the complete execution flow of your application:
251
+ const browserTracker = createTracePerf({
252
+ trackingMode: TrackingMode.BALANCED
253
+ });
241
254
 
242
- 1. **Using the `createTrackable` method** (recommended)
243
- 2. **Using nested `track` calls**
255
+ // Track a DOM operation
256
+ browserTracker.track(() => {
257
+ document.getElementById('output').textContent = 'Updated';
258
+ }, { label: 'updateDOM' });
259
+ ```
244
260
 
245
- #### Using createTrackable (Recommended)
261
+ ## Advanced Tracking Features
246
262
 
247
- The `createTrackable` method creates tracked versions of your functions that can be used in place of the original functions:
263
+ ### Tracking with Different Modes
248
264
 
249
265
  ```javascript
250
- function fetchData() {
251
- processData();
252
- calculateResults();
253
- }
254
-
255
- function processData() {
256
- // Some processing logic
257
- }
258
-
259
- function calculateResults() {
260
- // Some calculation logic
261
- }
266
+ const { createTracePerf, TrackingMode } = require('traceperf');
262
267
 
263
- // Create tracked versions of all functions
264
- const trackedFetchData = tracePerf.createTrackable(fetchData, { label: 'fetchData' });
265
- const trackedProcessData = tracePerf.createTrackable(processData, { label: 'processData' });
266
- const trackedCalculateResults = tracePerf.createTrackable(calculateResults, { label: 'calculateResults' });
267
-
268
- // Replace the global references to enable tracking
269
- global.processData = trackedProcessData;
270
- global.calculateResults = trackedCalculateResults;
271
-
272
- // Execute the tracked top-level function
273
- trackedFetchData();
274
- ```
268
+ // Performance mode - minimal overhead
269
+ const performanceTracker = createTracePerf({
270
+ trackingMode: TrackingMode.PERFORMANCE
271
+ });
275
272
 
276
- This will produce a complete execution flow chart showing all nested function calls:
273
+ // Balanced mode - moderate detail with reasonable overhead
274
+ const balancedTracker = createTracePerf({
275
+ trackingMode: TrackingMode.BALANCED
276
+ });
277
277
 
278
+ // Detailed mode - maximum information
279
+ const detailedTracker = createTracePerf({
280
+ trackingMode: TrackingMode.DETAILED
281
+ });
278
282
  ```
279
- Execution Flow:
280
- ┌──────────────────────────────┐
281
- │ fetchData │ ⏱ 200ms
282
- └──────────────────────────────┘
283
- │
284
- ▼
285
- ┌──────────────────────────────┐
286
- │ processData │ ⏱ 500ms ⚠️ SLOW
287
- └──────────────────────────────┘
288
- │
289
- ▼
290
- ┌──────────────────────────────┐
291
- │ calculateResults │ ⏱ 300ms
292
- └──────────────────────────────┘
293
- ```
294
-
295
- #### Using Nested Track Calls
296
283
 
297
- For more complex scenarios, you can use nested `track` calls:
284
+ ### Using Thresholds to Filter Results
298
285
 
299
286
  ```javascript
300
- tracePerf.track(() => {
301
- // Top-level function logic
302
-
303
- tracePerf.track(() => {
304
- // Nested function logic
305
-
306
- tracePerf.track(() => {
307
- // Deeply nested function logic
308
- }, { label: 'deeplyNestedFunction' });
309
-
310
- }, { label: 'nestedFunction' });
311
-
312
- }, { label: 'topLevelFunction' });
313
- ```
314
-
315
- #### Controlling Nested Tracking
287
+ const { createTracePerf } = require('traceperf');
288
+ const tracker = createTracePerf();
316
289
 
317
- You can control nested tracking with the following option:
290
+ // Only log functions that take more than 50ms
291
+ tracker.track(slowFunction, { threshold: 50 });
318
292
 
319
- ```javascript
320
- // Disable nested tracking entirely
321
- tracePerf.track(fetchData, { enableNestedTracking: false });
293
+ // Different thresholds for different functions
294
+ tracker.track(criticalFunction, { threshold: 10 }); // Low threshold for critical paths
295
+ tracker.track(backgroundTask, { threshold: 200 }); // Higher threshold for background tasks
322
296
  ```
323
297
 
324
- For more examples, see the `examples/nested-tracking.js` and `examples/auto-tracking-example.js` files in the repository.
325
-
326
- ## API Reference for Nested Tracking
327
-
328
- ### createTrackable
298
+ ### Memory Tracking
329
299
 
330
300
  ```javascript
331
- tracePerf.createTrackable(fn, options)
301
+ const { createTracePerf } = require('traceperf');
302
+ const tracker = createTracePerf({ trackMemory: true });
303
+
304
+ // Track memory usage for memory-intensive operations
305
+ const result = tracker.track(() => {
306
+ // Memory-intensive operations
307
+ const largeArray = new Array(1000000).fill(Math.random());
308
+ return processArray(largeArray);
309
+ }, { label: 'memoryIntensiveOperation' });
332
310
  ```
333
311
 
334
- Creates a tracked version of a function that can be used for nested function tracking.
312
+ For more examples, see the example files in the `examples/` directory.
335
313
 
336
- - `fn`: The function to make trackable
337
- - `options`: Options for tracking
338
- - `label`: Custom label for the function (defaults to function name)
339
- - `threshold`: Performance threshold in milliseconds
340
- - `includeMemory`: Whether to include memory usage tracking
341
- - `enableNestedTracking`: Whether to enable nested tracking (default: true)
314
+ ## License
342
315
 
343
- Returns a new function that, when called, will track the execution of the original function.
316
+ MIT
344
317
 
345
- ### Track Options for Nested Tracking
318
+ ## Website
346
319
 
347
- When using the `track` method, you can control nested tracking with these options:
320
+ Visit our website at [traceperf.com](https://traceperf.com) for more information, interactive examples, and detailed documentation.
348
321
 
349
- ```javascript
350
- tracePerf.track(fn, {
351
- // ... other options
352
- enableNestedTracking: true, // Enable/disable nested tracking
353
- });
354
- ```