📖 MemGuard Documentation

🚀 Installation

Basic Installation (Free)

pip install memguard

Pro Installation

pip install memguard[pro]
Pro License Required: Pro features require a valid license key. Get your Pro license for $79.

⚡ Quick Start

Basic Usage (Free)

import memguard # Start basic monitoring memguard.protect( threshold_mb=50, sample_rate=0.1, # 10% sampling patterns=['handles', 'caches'] ) # Analyze current state report = memguard.analyze() print(f"Health Score: {report.health_score}/100") # Stop monitoring memguard.stop()

Pro Usage (Automatic Cleanup)

import memguard # Pro with automatic cleanup memguard.protect( threshold_mb=50, sample_rate=0.1, patterns=['handles', 'caches', 'cycles'], license_key="YOUR-PRO-LICENSE-KEY", auto_cleanup=True # Pro feature ) # Get detailed Pro report report = memguard.analyze() print(f"Monthly savings: ${report.estimated_monthly_cost_usd:.2f}") # View strategic insights if hasattr(report, 'advanced_health_metrics'): metrics = report.advanced_health_metrics print("Strategic insights:", metrics['strategic_insights'])
Pro Benefit: With auto_cleanup=True, MemGuard automatically fixes memory leaks as they occur, saving you money without manual intervention.

✨ Pro Features

MemGuard Pro includes advanced features for production environments:

🔧 Automatic Cleanup

Automatically fixes memory leaks as they occur, preventing cost accumulation.

memguard.protect(auto_cleanup={ 'handles': True, # Auto-fix file/socket handles 'caches': True, # Auto-limit cache growth 'cycles': True # Auto-break reference cycles })

📊 Strategic Insights

Get architectural guidance beyond basic leak detection:

report = memguard.analyze() metrics = report.advanced_health_metrics print("Risk Assessment:", metrics['risk_assessment']) print("Strategic Insights:", metrics['strategic_insights']) print("Memory Efficiency:", metrics['memory_efficiency'])

🎯 Custom Patterns

Define custom leak patterns for your specific application:

memguard.protect( custom_patterns={ 'redis_connections': { 'pattern': r'redis.*connection.*leak', 'threshold': 100, 'cleanup_strategy': 'close_connections' } } )

🏢 Enterprise Reporting

Detailed reports for compliance and monitoring:

report = memguard.analyze(format='enterprise') report.export_pdf('memory_report.pdf') report.export_csv('metrics.csv')

⚙️ Configuration

Production Configuration

# Recommended production settings memguard.protect( threshold_mb=100, # Higher threshold for production sample_rate=0.05, # 5% sampling for minimal overhead patterns=['caches'], # Focus on high-value cache leaks poll_interval_s=60, # Check every minute background=True, # Non-blocking operation license_key="YOUR-KEY", # Pro license auto_cleanup={'caches': True} )

Development Configuration

# More aggressive monitoring for development memguard.protect( threshold_mb=10, # Lower threshold sample_rate=1.0, # 100% sampling patterns=['handles', 'caches', 'cycles', 'timers'], poll_interval_s=10, # Frequent checks aggressive_mode=True # Pro feature )

Environment Variables

# Set via environment variables export MEMGUARD_LICENSE_KEY="your-license-key" export MEMGUARD_THRESHOLD_MB=50 export MEMGUARD_SAMPLE_RATE=0.1 export MEMGUARD_AUTO_CLEANUP=true

📚 API Reference

memguard.protect()

Start memory leak monitoring and prevention.

memguard.protect( threshold_mb: float = 100.0, # Memory threshold in MB sample_rate: float = 0.1, # Sampling rate (0.0-1.0) patterns: List[str] = ['handles'], # Leak patterns to detect poll_interval_s: float = 30.0, # Polling interval in seconds background: bool = True, # Run in background # Pro features license_key: str = None, # Pro license key auto_cleanup: Union[bool, dict] = False, # Enable automatic cleanup aggressive_mode: bool = False, # Aggressive detection mode custom_patterns: dict = None # Custom leak patterns )

memguard.analyze()

Analyze current memory state and get a report.

report = memguard.analyze( format: str = 'full', # Report format cost_analysis: bool = True # Include cost analysis ) # Report properties print(report.health_score) # 0-100 health score print(report.findings) # List of leak findings print(report.estimated_monthly_cost_usd) # Monthly cost estimate

memguard.stop()

Stop all monitoring and cleanup background processes.

memguard.stop()

memguard.get_status()

Get current monitoring status.

status = memguard.get_status() print(status['is_protecting']) # True if monitoring active print(status['active_guards']) # List of active guards

🔧 Troubleshooting

Common Issues

High CPU Usage: Reduce sample_rate or increase poll_interval_s. For production, use sample_rate=0.05 (5%) and poll_interval_s=60.
License Validation Failed: Check your internet connection and verify your license key. Pro features require Firebase connectivity.
No Leaks Detected: Ensure sample_rate > 0.0 and threshold_mb is appropriate for your application. Try sample_rate=1.0 for testing.

CLI Debugging

# Check MemGuard status memguard status # Run analysis with verbose output memguard analyze --format json # Test Pro features memguard start --license YOUR-KEY --auto-cleanup # Check for upgrades memguard upgrade --check

Getting Help

If you need additional support: