memvigil
v1.2.0
Published
A comprehensive Node.js memory management and monitoring library with real-time tracking capabilities.
Maintainers
Readme
memvigil
A comprehensive Node.js memory management and monitoring library with real-time tracking capabilities.
Table of Contents
- Installation
- Features
- Quick Start
- Usage Examples
- TypeScript Support
- API Reference
- Production Best Practices
- License
Installation
npm install memvigilFeatures
- 🔍 Real-time memory monitoring
- 📊 CPU usage tracking
- 🚨 Automatic leak detection with severity levels
- 📸 Heap snapshot generation
- ♻️ Garbage collection analysis
- 📈 Performance metrics
- 🎯 Custom threshold alerts (warning & critical)
- 📉 Memory trend analysis with predictions
- ⚠️ Memory pressure detection
- 📄 Export reports (JSON/CSV)
- 📊 Comprehensive statistics
- 💻 Full TypeScript support
Quick Start
const MemoryMonitor = require("memvigil");
// Initialize with 200MB threshold
const monitor = new MemoryMonitor(200 * 1024 * 1024);
// Set up basic event listeners
monitor.on("thresholdExceeded", (memoryUsage) => {
console.log(
"Memory threshold exceeded:",
`${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)}MB`
);
});
monitor.on("leakDetected", (details) => {
console.log("Memory leak detected:", details.message);
console.log("Suggestions:", details.suggestions);
});
// Start monitoring with 10-second intervals
monitor.startMonitoring(10000);Usage Examples
Basic Monitoring
const MemoryMonitor = require("memvigil");
// Initialize with 200MB threshold
const monitor = new MemoryMonitor(200 * 1024 * 1024);
// Start monitoring with 10-second intervals
monitor.startMonitoring(10000);Advanced Configuration with Options
const MemoryMonitor = require("memvigil");
const options = {
enableGC: true,
enablePredictions: true,
alertThresholds: {
warning: 150 * 1024 * 1024, // 150MB
critical: 200 * 1024 * 1024, // 200MB
},
};
const monitor = new MemoryMonitor(100 * 1024 * 1024, 1000, options);
// Listen for warning alerts
monitor.on("warningAlert", (alert) => {
console.log("Warning:", alert.message);
});
// Listen for critical alerts
monitor.on("criticalAlert", (alert) => {
console.log("Critical:", alert.message);
// Take immediate action
});
monitor.startMonitoring(5000);Memory Trend Analysis
monitor.on("memoryTrend", (trend) => {
console.log(`Memory trend: ${trend.direction}`);
console.log(`Rate: ${(trend.rate / 1024).toFixed(2)} KB/s`);
console.log(
`Predicted memory in 1 hour: ${(trend.prediction / 1024 / 1024).toFixed(
2
)} MB`
);
});
// Or get trend manually
const trend = monitor.analyzeMemoryTrend();
if (trend && trend.direction === "increasing") {
console.log("Memory is growing!");
}Memory Pressure Detection
const pressure = monitor.detectMemoryPressure();
if (pressure.isUnderPressure) {
console.log(`Memory pressure level: ${pressure.pressureLevel}`);
console.log("Contributing factors:", pressure.factors);
if (pressure.pressureLevel === "critical") {
// Take emergency action
monitor.takeHeapSnapshot();
}
}Export Reports
// Export to JSON
const jsonPath = await monitor.exportReport("json", "./memory-report.json");
console.log("Report exported to:", jsonPath);
// Export to CSV
const csvPath = await monitor.exportReport("csv", "./memory-report.csv");
console.log("CSV exported to:", csvPath);Comprehensive Statistics
const stats = monitor.getStatistics();
console.log("Memory Statistics:");
console.log(
` Current: ${(stats.memory.current.heapUsed / 1024 / 1024).toFixed(2)} MB`
);
console.log(` Average: ${(stats.memory.average / 1024 / 1024).toFixed(2)} MB`);
console.log(
` Peak: ${(stats.memory.peak.value / 1024 / 1024).toFixed(
2
)} MB at ${new Date(stats.memory.peak.timestamp)}`
);
console.log("CPU Statistics:");
console.log(` Current user: ${stats.cpu.current.user}μs`);
console.log(` Average user: ${stats.cpu.average.user}μs`);
console.log("Performance Impact:");
console.log(` Average: ${stats.performance.averageTimeMs.toFixed(3)} ms`);
console.log(` Total samples: ${stats.performance.count}`);Enhanced Leak Detection
monitor.on("leakDetected", (result) => {
console.log(`Leak detected with ${result.severity} severity`);
console.log(`Trend: ${(result.trend * 100).toFixed(2)}%`);
console.log("Suggestions:", result.suggestions);
if (result.severity === "critical") {
// Automatically take heap snapshot
monitor.takeHeapSnapshot();
}
});
// Run leak detection
await monitor.detectLeaks(60000, 0.1, 5);Production Best Practices
Appropriate Monitoring Intervals
// Use longer intervals in production monitor.startMonitoring(30000); // 30 secondsResource Management
// Clean up old snapshots monitor.on("heapSnapshot", (filePath) => { // Keep only last 5 snapshots cleanupOldSnapshots(5); });Error Handling
monitor.on("error", (error) => { logger.error("Memory monitor error:", error); });Performance Impact Monitoring
setInterval(() => { const impact = monitor.getPerformanceImpact(); if (impact.averageTimeMs > 100) { // If overhead exceeds 100ms monitor.stopMonitoring(); } }, 60000);
TypeScript Support
memvigil includes full TypeScript definitions. Simply import and use with full type safety:
import MemoryMonitor, { MonitorOptions, MemoryTrend } from "memvigil";
const options: MonitorOptions = {
enableGC: true,
enablePredictions: true,
alertThresholds: {
warning: 150 * 1024 * 1024,
critical: 200 * 1024 * 1024,
},
};
const monitor = new MemoryMonitor(100 * 1024 * 1024, 1000, options);
monitor.on("memoryTrend", (trend: MemoryTrend) => {
console.log(`Trend: ${trend.direction}, Prediction: ${trend.prediction}`);
});
monitor.startMonitoring(5000);All types are exported and available for use in your TypeScript projects.
API Reference
Constructor
new MemoryMonitor(threshold?, maxHistorySize?, options?)threshold(number, default: 100MB): Memory threshold in bytesmaxHistorySize(number, default: 1000): Maximum history entries to keepoptions(object, optional):enableGC(boolean, default: true): Enable garbage collection trackingenablePredictions(boolean, default: true): Enable memory trend predictionsalertThresholds(object, optional):warning(number): Warning threshold in bytescritical(number): Critical threshold in bytes
Methods
startMonitoring(interval?)- Start monitoring (default: 5000ms)stopMonitoring()- Stop monitoringtakeHeapSnapshot(automatic?)- Generate heap snapshotgetMemoryUsageReport()- Get memory historygetCpuUsageReport()- Get CPU historygetGCReport()- Get GC historyclearHistory()- Clear all historydetectLeaks(duration?, threshold?, samples?)- Detect memory leaksanalyzeMemoryTrend()- Analyze memory trendsdetectMemoryPressure()- Detect memory pressuregetStatistics()- Get comprehensive statisticsexportReport(format?, filePath?)- Export report (json/csv)getMemoryBreakdown()- Get detailed memory breakdowngetPerformanceImpact()- Get performance impact metricscheckNodeCompatibility()- Check Node.js version compatibility
Events
thresholdExceeded- Emitted when memory exceeds thresholdmemoryStats- Emitted on each memory measurementcpuStats- Emitted on each CPU measurementleakDetected- Emitted when a leak is detectedheapSnapshot- Emitted when a heap snapshot is createdmemoryTrend- Emitted when memory trend is analyzedwarningAlert- Emitted when warning threshold is exceededcriticalAlert- Emitted when critical threshold is exceededgcStats- Emitted on GC statistics updatereportExported- Emitted when a report is exportederror- Emitted on errorswarning- Emitted for warningsinfo- Emitted for informational messages
License
MIT License - see LICENSE file for details
