bodhi-node-profiler
Version:
A lightweight, zero-configuration performance profiler for Node.js applications with real-time dashboard
426 lines (327 loc) ⢠11.9 kB
Markdown
# Bodhi Node Profiler
<div align="center">
š A lightweight, zero-configuration performance profiler for Node.js applications with real-time dashboard
[](https://www.npmjs.com/package/bodhi-node-profiler)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
[](https://github.com/BODHEESH/bodhi-node-profiler/pulls)
</div>
<p align="center">
<a href="#quick-start">Quick Start</a> ā¢
<a href="#features">Features</a> ā¢
<a href="#usage-examples">Examples</a> ā¢
<a href="#configuration-options">Configuration</a> ā¢
<a href="#support">Support</a>
</p>
## šÆ Overview
Unlock the full potential of your Node.js applications with Bodhi Node Profiler! Monitor, debug, and optimize your application's performance in real-time with minimal setup. Whether you're debugging in development or monitoring in production, Bodhi Node Profiler provides the insights you need.
### ā”ļø Why Choose Bodhi Node Profiler?
- š **One-Line Integration**: Start profiling with minimal code changes
- š **Real-Time Dashboard**: Beautiful, modern dashboard with live metrics
- š **Comprehensive Metrics**: CPU, Memory, Event Loop, and API performance
- ā” **Production Ready**: Low overhead (<50MB memory, <1% CPU)
- š ļø **Developer Friendly**: TypeScript & JavaScript support, Express.js integration
### š New Features!
- š **Enhanced Real-time Charts**: Beautiful visualizations using Chart.js
- šÆ **Accurate CPU Monitoring**: Improved CPU usage calculation
- ā±ļø **API Response Time Tracking**: Monitor endpoint performance
- š **Event Loop Monitoring**: Track event loop delays
- š” **Smart Status Indicators**: Visual health status for each metric
- ā **Uptime Tracking**: Monitor your application's uptime
- šØ **Modern UI**: Clean, responsive dashboard design with Tailwind CSS
## Quick Start
### 1. Install
```bash
npm install bodhi-node-profiler
```
### 2. Basic Usage
```javascript
const express = require('express');
const { BodhiProfiler } = require('bodhi-node-profiler');
const app = express();
// Initialize profiler with modern dashboard
const profiler = new BodhiProfiler({
serviceName: 'my-app',
port: 45680, // Dashboard port
enableWebDashboard: true
});
app.use(profiler.middleware());
app.listen(3000, () => {
console.log('Server running on port 3000');
console.log('Profiler dashboard available at http://localhost:45680/profiler');
});
```
### 3. Access the Dashboard
Once your application is running, access the beautiful real-time dashboard at:
```
http://localhost:45680/profiler
```
> Note: The dashboard port (45680) can be configured using the `port` option in the BodhiProfiler constructor.
## Dashboard Features
The new dashboard provides:
- š **Real-time Metrics**
- CPU Usage with status indicators (Good/Warning/High)
- Memory Usage and allocation tracking
- Event Loop Delay monitoring
- API Response Time analysis
- š **Live Charts**
- CPU utilization trends
- Memory consumption patterns
- Event loop performance
- API response times
- š» **System Information**
- Total Memory usage
- Application Uptime
- Last Updated timestamp
- šØ **Modern Design**
- Clean, responsive layout
- Intuitive metric cards
- Status indicators
- Beautiful animations
## Features
### š Real-time Performance Monitoring
- CPU usage tracking
- Memory leak detection
- Event loop delay monitoring
- API response time analysis
- Custom metrics support
### š Comprehensive API Profiling
- Automatic endpoint detection
- Response time tracking
- Error rate monitoring
- Request/Response logging
- Route usage analytics
### ā” Production-Ready
- Minimal overhead
- Safe for production use
- Configurable logging
- Alert thresholds
- No external dependencies
### š ļø Developer Experience
- TypeScript support
- Express.js integration
- Beautiful web dashboard
- Easy configuration
- Detailed documentation
## Usage Examples
### 1. REST API Server
```javascript
const express = require('express');
const { BodhiProfiler } = require('bodhi-node-profiler');
const app = express();
// Custom configuration
const profiler = new BodhiProfiler({
logPath: './logs',
sampleInterval: 1000,
enableWebDashboard: true,
port: 8080
});
app.use(profiler.middleware());
// Your routes will be automatically profiled!
app.get('/api/users', async (req, res) => {
const users = await db.getUsers();
res.json(users);
});
```
### 2. GraphQL Server
```javascript
const { ApolloServer } = require('apollo-server');
const { BodhiProfiler } = require('bodhi-node-profiler');
const profiler = new BodhiProfiler();
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [{
requestDidStart: () => ({
willSendResponse: (requestContext) => {
// Track GraphQL operation performance
profiler.trackOperation({
type: 'GraphQL',
name: requestContext.operationName,
duration: requestContext.request.duration
});
}
})
}]
});
```
### 3. Microservices Architecture
```javascript
const express = require('express');
const { BodhiProfiler } = require('bodhi-node-profiler');
// Initialize with service-specific config
const profiler = new BodhiProfiler({
serviceName: 'auth-service',
logPath: './logs/auth-service',
tags: ['microservice', 'auth'],
alertThresholds: {
memory: 1024 * 1024 * 1024, // 1GB
cpu: 80, // 80% CPU usage
responseTime: 1000 // 1 second
}
});
// Get real-time metrics
app.get('/health', (req, res) => {
const metrics = profiler.getMetrics();
res.json({
status: 'healthy',
...metrics
});
});
```
### 4. Background Jobs
```javascript
const { BodhiProfiler } = require('bodhi-node-profiler');
const profiler = new BodhiProfiler({
logPath: './logs/jobs'
});
async function processQueue() {
const start = Date.now();
try {
await heavyJob();
profiler.trackOperation({
type: 'Job',
name: 'processQueue',
duration: Date.now() - start
});
} catch (error) {
profiler.trackError({
type: 'Job',
name: 'processQueue',
error
});
}
}
```
## Advanced Features
### 1. Custom Metrics
```javascript
// Track custom business metrics
profiler.trackMetric({
name: 'activeUsers',
value: getUserCount(),
tags: ['business', 'users']
});
```
### 2. Performance Alerts
```javascript
const profiler = new BodhiProfiler({
alerts: {
onHighMemory: (usage) => notifyDevOps('High memory usage detected', usage),
onHighCPU: (usage) => scaleService(),
onSlowEndpoint: (data) => logPerformanceIssue(data)
}
});
```
### 3. Memory Leak Detection
```javascript
const profiler = new BodhiProfiler({
memoryLeakDetection: true,
heapSnapshotInterval: 3600000 // 1 hour
});
```
## Log Management
The profiler now includes smart log management features:
#### Log Rotation
- Automatic log rotation based on size or date
- Compressed archives for space efficiency
- Configurable retention periods
```javascript
logging: {
rotation: {
maxFiles: '7d', // Keep 7 days of logs
maxSize: '5m', // Rotate at 5MB
datePattern: 'YYYY-MM-DD',
compress: true // Compress old logs
}
}
```
#### Log Cleanup
- Automatic cleanup of old logs
- Configurable retention period
- Separate archive directory
```javascript
logging: {
cleanup: {
enabled: true,
maxAge: '30d' // Delete logs older than 30 days
}
}
```
#### Metric Thresholds
Only log metrics when they exceed specified thresholds:
```javascript
metrics: {
cpu: {
threshold: 70 // CPU usage > 70%
},
memory: {
threshold: 80 // Memory usage > 80%
},
eventLoop: {
threshold: 100 // Delay > 100ms
},
api: {
responseTime: {
threshold: 1000 // Response time > 1s
}
}
}
```
## Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| logPath | string | './logs' | Directory for performance logs |
| port | number | 8080 | Dashboard port |
| sampleInterval | number | 1000 | Metrics collection interval (ms) |
| enableWebDashboard | boolean | true | Enable/disable web dashboard |
| serviceName | string | undefined | Service identifier for distributed systems |
| tags | string[] | [] | Tags for metric categorization |
| alertThresholds | object | {} | Performance alert thresholds |
## Why Bodhi Node Profiler?
1. **Zero Configuration**: Works out of the box with smart defaults
2. **Low Overhead**: Minimal impact on application performance
3. **Real-time Insights**: Instant visibility into performance issues
4. **No External Dependencies**: Everything you need is included
5. **TypeScript Support**: Full type definitions included
## Performance Impact
- Memory Overhead: < 50MB
- CPU Overhead: < 1%
- Response Time Impact: < 0.5ms
## Best Practices
1. **Development**:
- Enable all features for maximum insight
- Use lower sampling intervals for detailed data
2. **Production**:
- Adjust sampling intervals based on traffic
- Enable alerts for proactive monitoring
- Use log rotation for long-running services
---
## š A Note from the Developer
Hey there! I'm Bodheesh VC, a passionate Node.js developer who believes in making development easier and more efficient for everyone. I created Bodhi Node Profiler because I felt the pain of debugging performance issues in production applications and wanted a simple, lightweight solution that just works.
This project is my contribution to the amazing Node.js community that has given me so much. It's built with love, attention to detail, and a focus on developer experience. Whether you're building a small API or a large microservices architecture, I hope this tool makes your development journey a little bit easier.
I'm actively maintaining this project and would love to hear your feedback! Feel free to reach out on [Twitter](https://twitter.com/bodheeshvc) or [LinkedIn](https://linkedin.com/in/bodheeshvc) if you have questions or just want to chat about Node.js performance optimization.
Let's make the Node.js ecosystem better together! š
---
## Contributing
I believe in the power of community! If you'd like to contribute, here's how you can help:
- š Report bugs and issues on our [GitHub Issues](https://github.com/BODHEESH/bodhi-node-profiler/issues)
- š” Suggest new features
- š Improve documentation
- š§ Submit [pull requests](https://github.com/BODHEESH/bodhi-node-profiler/pulls)
- ā Star the project if you find it useful!
Check out our [Contributing Guide](CONTRIBUTING.md) for more details.
## Support
Need help? I'm here for you!
- š§ Email: bodheeshvc.developer@gmail.com
- š¦ Twitter: [@bodheeshvc](https://twitter.com/bodheeshvc)
- š¼ LinkedIn: [bodheeshvc](https://linkedin.com/in/bodheeshvc)
- š¬ Discord: [Join our community](https://discord.gg/bodhi-profiler)
## License
MIT Ā© [Bodheesh VC](https://github.com/BODHEESH)
---
<div align="center">
Made with ā¤ļø by <a href="https://github.com/BODHEESH">Bodheesh VC</a>
<br />
If you find this tool helpful, consider giving it a āļø on <a href="https://github.com/BODHEESH/bodhi-node-profiler">GitHub</a>!
</div>