Claude
Skills
Sign in
โ† Back

resource-monitor

Included with Lifetime
$97 forever

Monitor system resources (CPU, memory, disk, network) during development and production.

General

What this skill does


# Resource Monitor Skill

Monitor system resources (CPU, memory, disk, network) during development and production.

## Instructions

You are a system resource monitoring expert. When invoked:

1. **Monitor Resources**:
   - CPU usage and load average
   - Memory usage (RAM and swap)
   - Disk usage and I/O
   - Network traffic and connections
   - Process-level metrics

2. **Analyze Patterns**:
   - Identify resource-intensive processes
   - Detect memory leaks
   - Find CPU bottlenecks
   - Monitor disk space trends
   - Track network bandwidth usage

3. **Set Alerts**:
   - CPU usage thresholds
   - Memory limits
   - Disk space warnings
   - Unusual network activity

4. **Provide Recommendations**:
   - Resource optimization strategies
   - Scaling recommendations
   - Configuration improvements
   - Performance tuning

## Resource Metrics

### CPU Monitoring
```bash
# Current CPU usage
top -bn1 | grep "Cpu(s)"

# Per-core usage
mpstat -P ALL 1

# Process CPU usage
ps aux --sort=-%cpu | head -10

# Load average
uptime

# Node.js CPU profiling
node --prof app.js
node --prof-process isolate-*.log
```

### Memory Monitoring
```bash
# Memory usage
free -h

# Detailed memory info
cat /proc/meminfo

# Process memory usage
ps aux --sort=-%mem | head -10

# Memory map for specific process
pmap -x <PID>

# Node.js memory usage
node --inspect app.js
# Chrome DevTools -> Memory
```

### Disk Monitoring
```bash
# Disk space
df -h

# Disk I/O
iostat -x 1

# Large files/directories
du -h --max-depth=1 / | sort -hr | head -20

# Disk usage by directory
ncdu /

# Monitor disk writes
iotop
```

### Network Monitoring
```bash
# Network connections
netstat -tunapl

# Active connections
ss -s

# Bandwidth usage
iftop

# Network traffic
nload

# Connection states
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
```

## Monitoring Scripts

### Node.js Resource Monitor
```javascript
// resource-monitor.js
const os = require('os');

class ResourceMonitor {
  constructor(interval = 5000) {
    this.interval = interval;
    this.startTime = Date.now();
  }

  start() {
    console.log('๐Ÿ” Resource Monitor Started\n');
    this.logResources();
    setInterval(() => this.logResources(), this.interval);
  }

  logResources() {
    const uptime = Math.floor((Date.now() - this.startTime) / 1000);
    const cpu = this.getCPUUsage();
    const memory = this.getMemoryUsage();
    const load = os.loadavg();

    console.clear();
    console.log('๐Ÿ“Š System Resources');
    console.log('='.repeat(50));
    console.log(`Uptime: ${this.formatUptime(uptime)}`);
    console.log('');

    console.log('CPU:');
    console.log(`  Usage: ${cpu.toFixed(2)}%`);
    console.log(`  Load Average: ${load[0].toFixed(2)}, ${load[1].toFixed(2)}, ${load[2].toFixed(2)}`);
    console.log(`  Cores: ${os.cpus().length}`);
    console.log('');

    console.log('Memory:');
    console.log(`  Total: ${this.formatBytes(memory.total)}`);
    console.log(`  Used: ${this.formatBytes(memory.used)} (${memory.percentage.toFixed(2)}%)`);
    console.log(`  Free: ${this.formatBytes(memory.free)}`);
    this.printProgressBar('Memory', memory.percentage);
    console.log('');

    const processMemory = process.memoryUsage();
    console.log('Process Memory:');
    console.log(`  RSS: ${this.formatBytes(processMemory.rss)}`);
    console.log(`  Heap Total: ${this.formatBytes(processMemory.heapTotal)}`);
    console.log(`  Heap Used: ${this.formatBytes(processMemory.heapUsed)}`);
    console.log(`  External: ${this.formatBytes(processMemory.external)}`);
    console.log('');

    this.checkThresholds(cpu, memory);
  }

  getCPUUsage() {
    const cpus = os.cpus();
    let totalIdle = 0;
    let totalTick = 0;

    cpus.forEach(cpu => {
      for (const type in cpu.times) {
        totalTick += cpu.times[type];
      }
      totalIdle += cpu.times.idle;
    });

    const idle = totalIdle / cpus.length;
    const total = totalTick / cpus.length;
    const usage = 100 - ~~(100 * idle / total);

    return usage;
  }

  getMemoryUsage() {
    const total = os.totalmem();
    const free = os.freemem();
    const used = total - free;
    const percentage = (used / total) * 100;

    return { total, free, used, percentage };
  }

  formatBytes(bytes) {
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(2)} ${units[unitIndex]}`;
  }

  formatUptime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours}h ${minutes}m ${secs}s`;
  }

  printProgressBar(label, percentage) {
    const width = 40;
    const filled = Math.floor(width * percentage / 100);
    const empty = width - filled;
    const bar = 'โ–ˆ'.repeat(filled) + 'โ–‘'.repeat(empty);

    let color = '\x1b[32m'; // Green
    if (percentage > 70) color = '\x1b[33m'; // Yellow
    if (percentage > 85) color = '\x1b[31m'; // Red

    console.log(`  ${color}[${bar}] ${percentage.toFixed(1)}%\x1b[0m`);
  }

  checkThresholds(cpu, memory) {
    const warnings = [];

    if (cpu > 80) {
      warnings.push(`โš ๏ธ  High CPU usage: ${cpu.toFixed(2)}%`);
    }

    if (memory.percentage > 80) {
      warnings.push(`โš ๏ธ  High memory usage: ${memory.percentage.toFixed(2)}%`);
    }

    if (warnings.length > 0) {
      console.log('\nWarnings:');
      warnings.forEach(w => console.log(`  ${w}`));
    }
  }
}

// Start monitoring
const monitor = new ResourceMonitor(5000);
monitor.start();
```

### Python Resource Monitor
```python
# resource_monitor.py
import psutil
import time
from datetime import datetime

class ResourceMonitor:
    def __init__(self, interval=5):
        self.interval = interval

    def start(self):
        print("๐Ÿ” Resource Monitor Started\n")
        while True:
            self.log_resources()
            time.sleep(self.interval)

    def log_resources(self):
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        net = psutil.net_io_counters()

        print("\033[2J\033[H")  # Clear screen
        print("๐Ÿ“Š System Resources")
        print("=" * 50)
        print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

        print("CPU:")
        print(f"  Usage: {cpu_percent}%")
        print(f"  Cores: {psutil.cpu_count()}")
        self.print_progress_bar("CPU", cpu_percent)
        print()

        print("Memory:")
        print(f"  Total: {self.format_bytes(memory.total)}")
        print(f"  Used: {self.format_bytes(memory.used)} ({memory.percent}%)")
        print(f"  Free: {self.format_bytes(memory.available)}")
        self.print_progress_bar("Memory", memory.percent)
        print()

        print("Disk:")
        print(f"  Total: {self.format_bytes(disk.total)}")
        print(f"  Used: {self.format_bytes(disk.used)} ({disk.percent}%)")
        print(f"  Free: {self.format_bytes(disk.free)}")
        self.print_progress_bar("Disk", disk.percent)
        print()

        print("Network:")
        print(f"  Sent: {self.format_bytes(net.bytes_sent)}")
        print(f"  Received: {self.format_bytes(net.bytes_recv)}")
        print()

        self.check_thresholds(cpu_percent, memory.percent, disk.percent)

    def format_bytes(self, bytes):
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if bytes < 1024:
                return f"{bytes:.2f} {unit}"
            bytes /= 1024
        return f"{bytes:.2f} PB"

    def print_progress_bar(self, label, percentage):
        width = 40
        filled = int(width * percentage / 100)
        empty = width - filled
        bar = 'โ–ˆ' * filled + 'โ–‘' * empty

        if percentage > 85:
            color = '\033[91m'  # Red
        elif percentage > 70:
            color = '\033[93m'  # Yellow
        else:
            color =

Related in General