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.
pip install psutil
Python code
32 linesimport 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
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
- Use `timeit` to calibrate the exact loop overhead for more precise intervals
- 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
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Batch Rename Hundreds of Files in Python easy
- Benchmark File Read and Write Speed in Python medium
Keep learning
Related tutorials and quizzes for this topic.