pm2-monitor-next
v1.2.4
Published
Stateless PM2 monitoring plugin for real-time metrics collection and export to external systems (Prometheus, custom services, etc.)
Readme
PM2 Monitor Next
A stateless, lightweight PM2 monitoring plugin for real-time metrics collection and multi-destination export. Designed with simplicity, zero data retention, and flexible integrations in mind.
✨ Features
- Stateless Architecture - No persistent storage; designed for real-time data collection and forwarding only
- Multi-destination Export - HTTP pull (Prometheus-compatible), HTTP push, and custom integrations
- Real-time Alerts - CPU, memory, and process restart alerts via Email, DingTalk, Feishu, and WeChat Work
- Event-driven Monitoring - Captures PM2 events (crashes, restarts, etc.)
- Zero Configuration Overhead - Works out of the box with sensible defaults
- Dynamic Configuration - Update settings on-the-fly with
pm2 set - Low Memory Footprint - ~10-50MB memory usage regardless of process count
📋 Stateless Design Philosophy
Unlike traditional monitoring solutions, PM2 Monitor Next follows a stateless approach:
- ❌ No persistent storage - Metrics are computed on-demand from PM2
- ❌ No database dependencies - Zero disk I/O overhead
- ✅ Ephemeral memory - Only current and previous cycle metrics are kept
- ✅ Horizontal scalability - Deploy multiple instances without coordination
- ✅ Fast failure recovery - No data loss or migration on restart
This design makes it ideal for:
- Cloud deployments where storage is expensive
- High-performance environments where disk I/O matters
- Microservices architectures with multiple PM2 instances
- Integration with external time-series databases (Prometheus, InfluxDB, etc.)
🚀 Quick Start
1. Installation
npm install pm2-monitor-nextOr as a PM2 module:
pm2 install pm2-monitor-next2. Start Monitoring
# Direct start
npm start
# Or as PM2 process
pm2 start app.js --name pm2-monitor-next
# Or as PM2 module (recommended)
pm2 install .3. Access Metrics
# Real-time metrics (Prometheus format)
curl http://localhost:9999/metrics
# JSON format
curl http://localhost:9999/json
# Health check
curl http://localhost:9999/health📊 Configuration
Configure the module using pm2 set:
Collection Settings
# Polling interval (ms, default: 5000)
pm2 set pm2-monitor-next:poll_interval 5000
# HTTP metrics port (default: 9999)
pm2 set pm2-monitor-next:metrics_port 9999Push Mode (Optional)
# Target URL for pushing metrics
pm2 set pm2-monitor-next:push_url http://your-service.com/metrics
# Push interval (ms, default: 30000)
pm2 set pm2-monitor-next:push_interval 30000Alert Thresholds
# CPU threshold (%, default: 80)
pm2 set pm2-monitor-next:alert_cpu_threshold 80
# Memory threshold (bytes, default: 536870912 = 512MB)
pm2 set pm2-monitor-next:alert_memory_threshold 536870912
# Alert cooldown period (ms, default: 300000 = 5min)
pm2 set pm2-monitor-next:alert_cooldown 300000Error Log Monitoring
Monitor application error logs and send alerts when errors are detected:
# Monitor ALL error logs (any error triggers an alert)
pm2 set pm2-monitor-next:alert_error_log true
# OR monitor specific error keywords (case-insensitive)
# Use JSON array format
pm2 set pm2-monitor-next:alert_log_keywords '["database","timeout","connection"]'
# Or use comma-separated format
pm2 set pm2-monitor-next:alert_log_keywords "database,timeout,connection"Capabilities:
- Real-time error detection from application logs
- Two monitoring modes:
- Monitor all errors: Alert on every error log message
- Keyword-based: Alert only when specific keywords are detected
- Error message cleaning (removes
[Error]prefix automatically) - Cooldown protection applies to error alerts (same as other alert types)
- Supports all webhook platforms (Feishu, DingTalk, WeChat Work)
Email Alerts
pm2 set pm2-monitor-next:alert_email_smtp smtp.gmail.com
pm2 set pm2-monitor-next:alert_email_from [email protected]
pm2 set pm2-monitor-next:alert_email_to [email protected]Webhook Alerts
# DingTalk
pm2 set pm2-monitor-next:alert_dingtalk_webhook "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN"
# Feishu (飞书)
pm2 set pm2-monitor-next:alert_feishu_webhook "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_WEBHOOK_ID"
# WeChat Work
pm2 set pm2-monitor-next:alert_workwechat_webhook "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY"🔌 API Endpoints
GET /metrics
Returns metrics in Prometheus format:
# HELP pm2_process_cpu_percent CPU usage percentage
# TYPE pm2_process_cpu_percent gauge
pm2_process_cpu_percent{process_name="api-server"} 12.5
# HELP pm2_process_memory_bytes Memory usage in bytes
# TYPE pm2_process_memory_bytes gauge
pm2_process_memory_bytes{process_name="api-server"} 104857600
# HELP pm2_process_restarts Total restart count
# TYPE pm2_process_restarts counter
pm2_process_restarts{process_name="api-server"} 2GET /json
Returns metrics in JSON format:
{
"success": true,
"timestamp": 1700000000000,
"count": 2,
"data": [
{
"name": "api-server",
"pid": 12345,
"cpu": 12.5,
"memory": 104857600,
"status": "online",
"restarts": 2,
"uptime": 3600000,
"ts": 1700000000000
}
]
}GET /health
Health check endpoint:
{
"success": true,
"status": "healthy",
"timestamp": 1700000000000,
"architecture": "stateless"
}📈 Integration Examples
Prometheus
Add to prometheus.yml:
scrape_configs:
- job_name: 'pm2-monitor-next'
metrics_path: '/metrics'
scrape_interval: 30s
static_configs:
- targets: ['localhost:9999']Then query in Prometheus:
rate(pm2_process_cpu_percent[5m])
pm2_process_memory_bytes
pm2_process_restartsCustom HTTP Push
Configure push mode to send metrics to your service:
pm2 set pm2-monitor-next:push_url http://your-api.com/metrics
pm2 set pm2-monitor-next:push_interval 30000The monitor will POST metrics as JSON every 30 seconds.
Grafana Dashboard
Create a dashboard with:
- Data Source: Prometheus
- Metrics:
pm2_*queries - Alerts: Custom rules based on thresholds
🔔 Alert Types
| Alert | Trigger | Channels | |-------|---------|----------| | CPU Alert | Process CPU > threshold | Email, DingTalk, Feishu, WeChat | | Memory Alert | Process memory > threshold | Email, DingTalk, Feishu, WeChat | | Restart Alert | Process restart detected | Email, DingTalk, Feishu, WeChat | | Crash Alert | Process status = errored | Email, DingTalk, Feishu, WeChat | | Error Log Alert | Error log detected (all or keyword match) | Email, DingTalk, Feishu, WeChat |
Note: Alerts include cooldown protection to prevent alert storms (default: 5 minutes between alerts for same process/type). For error log alerts, cooldown applies per process (or per process + keyword combination in keyword mode).
🧪 Testing Webhooks
Test your webhook configuration using pm2 trigger:
# Test all configured webhooks
pm2 trigger pm2-monitor-next 'Test Alert'
# Test specific platforms
pm2 trigger pm2-monitor-next 'Test Feishu' # Feishu only
pm2 trigger pm2-monitor-next 'Test DingTalk' # DingTalk only
pm2 trigger pm2-monitor-next 'Test WeChat Work' # WeChat Work onlyResults will appear in PM2 logs:
pm2 logs pm2-monitor-next🏗️ Architecture
┌─────────────────────────────────────┐
│ PM2 Process Manager │
└─────────────┬───────────────────────┘
│
┌─────────┴─────────┐
│ │
▼ ▼
┌─────────────┐ ┌──────────────┐
│ Polling │ │ Event Bus │
│ (5s cycle) │ │ (Real-time) │
└─────────────┘ └──────────────┘
│ │
│ ┌─────────┴─────────┐
│ │ │
│ ▼ ▼
│ ┌──────────┐ ┌──────────────┐
│ │Standard │ │Error Logs │
│ │Events │ │(log:err) │
│ └──────────┘ └──────────────┘
│ │ │
└─────────┬─────────┬─────────┘
│ │
▼ ▼
┌─────────────────────────┐
│ Metrics & Error Monitor│
│ (Current + Prev) │
└─────────┬───────────────┘
│
┌─────────┴──────────┬──────────┬────────────┐
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────┐ ┌──────────┐ ┌─────────┐ ┌────────┐
│ HTTP Pull │ │HTTP Push │ │ Alerts │ │ Logs │
│ (/metrics) │ │(Custom) │ │(Webhooks│ │(stdout)│
└─────────────┘ └──────────┘ └─────────┘ └────────┘📂 Project Structure
pm2-monitor-next/
├── app.js # Main entry point
├── package.json # Dependencies & config
├── config.example.json # Configuration template
├── LICENSE # MIT License
├── README.md # This file
├── CONTRIBUTING.md # Contribution guidelines
├── CHANGELOG.md # Release history
├── .editorconfig # Editor config
├── .gitattributes # Git attributes
├── .gitignore # Git ignore rules
└── src/
├── collector.js # PM2 data collection
├── processor.js # Data formatting
├── log-monitor.js # Error log monitoring
├── alert/
│ ├── index.js # Alert orchestration
│ ├── email.js # Email alerts
│ └── webhook.js # Webhook alerts
└── exporters/
├── http-server.js # HTTP API server
└── push.js # HTTP push exporter🧪 Development
Prerequisites
- Node.js >= 12
- PM2 >= 5.0
Setup
git clone https://github.com/seakeys/pm2-monitor-next.git
cd pm2-monitor-next
npm installRunning
# Development mode
npm run dev
# Direct start
npm start
# As PM2 process
pm2 start app.js --name pm2-monitor-next📝 Dependencies
{
"pm2": "^5.3.0", // PM2 API
"@pm2/io": "^5.0.0", // PM2 module framework
"nodemailer": "^6.9.0" // Email sending
}Why no database dependency? The stateless design eliminates the need for persistent storage!
🚀 Deployment
As PM2 Module (Recommended)
# Local installation
pm2 install .
# Or from npm (after publishing)
pm2 install pm2-monitor-nextPersistent Startup
pm2 startup
pm2 saveDocker
FROM node:16-alpine
WORKDIR /app
COPY . .
RUN npm install --production
EXPOSE 9999
CMD ["npm", "start"]💡 Best Practices
- Polling interval: 5-15 seconds (avoid too frequent polling)
- Alert cooldown: 5-10 minutes (prevent alert storms)
- Prometheus scrape interval: Match or exceed polling interval
- Multiple instances: One per server, configure multiple targets in Prometheus
- Scaling: Deploy independently on each server; no coordination needed
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
📄 License
This project is licensed under the MIT License - see LICENSE file for details.
📞 Support
📚 Additional Resources
Next Steps:
- Install:
npm install pm2-monitor-next - Start:
npm startorpm2 install . - Access:
curl http://localhost:9999/metrics - Configure: Use
pm2 setcommands - Integrate: Connect to Prometheus or custom service
