Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Automatically Log CPU, RAM, and Disk Usage Every Minute in Python

This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.

Easy Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Requires third-party packages — install first
pip install psutil

Python code

32 lines
Python 3.9+
import psutil
import time
import csv
from pathlib import Path

LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60

def log_system_usage():
    """Write CPU, RAM, and disk usage to CSV every minute."""
    file_exists = LOG_FILE.exists()
    with open(LOG_FILE, mode="a", newline="") as f:
        writer = csv.writer(f)
        if not file_exists:
            writer.writerow(["Timestamp", "CPU%", "RAM%", "Disk%"])

        while True:
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
            cpu = psutil.cpu_percent(interval=1)
            ram = psutil.virtual_memory().percent
            disk = psutil.disk_usage("/").percent
            writer.writerow([timestamp, cpu, ram, disk])
            f.flush()
            time.sleep(INTERVAL_SECONDS - 1)  # adjust for 1s cpu sampling

if __name__ == "__main__":
    print(f"Logging system usage every {INTERVAL_SECONDS} seconds to {LOG_FILE}...")
    print("Press Ctrl+C to stop.")
    try:
        log_system_usage()
    except KeyboardInterrupt:
        print("\nLogging stopped.")

Output

stdout
Logging system usage every 60 seconds to system_usage_log.csv...
Press Ctrl+C to stop.
Logging stopped.

How it works

The script uses psutil to capture real-time system metrics: CPU percentage, memory usage, and disk utilization. The csv module writes rows to a file, appending a header only if the file is new. A while True loop runs indefinitely; each iteration sleeps for INTERVAL_SECONDS - 1 to account for the 1-second CPU polling delay, ensuring data is logged approximately every 60 seconds. The f.flush() call makes each row immediately visible in the file, even if the program is interrupted. A KeyboardInterrupt handler allows graceful shutdown.

Common mistakes

  • Forgetting to install psutil with pip
  • Not flushing the file handle causes last rows to be lost on Ctrl+C
  • Using sleep(60) without subtracting the CPU sampling time, leading to >60s intervals

Variations

  1. Use `timeit` to calibrate the exact loop overhead for more precise intervals
  2. Add logging of network I/O with `psutil.net_io_counters()`

Real-world use cases

  • Monitoring server health on a low-budget VPS without paid tools.
  • Gathering historical usage data to right-size cloud instances.
  • Triggering alerts when disk usage exceeds a threshold in a dev environment.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.