I'm focused on the user's need for a performance monitoring script. I've broken it down: the goal is to track CPU, memory, disk, and network usage, logging everything to a file. Now, I'm identifying the libraries I'll need.
Structuring the Code
I'm now outlining the script's structure: importing psutil, logging, and time. Then I'll establish the logging configuration, including the log file's name. After that, I'll need a loop to gather and record metrics at regular intervals. I'm considering error handling, too.
Considering Module Structure
I'm now focusing on modularity, mapping out functions for gathering metrics, initializing the CSV (including header creation), and writing rows. I'm also considering the try-except structure for graceful shutdown and error handling, making sure to close the file correctly.
Defining Implementation Steps
I'm now detailing the script's core components. First, I'm identifying the libraries and installing psutil. Next, I'm defining key functions: gathering metrics, setting up the CSV, and writing data. I'm prioritizing data format and deciding on snapshot-based metrics. Finally, I'm structuring a modular script with a try-except block, and console output.
Implementing File I/O
I'm now focusing on the CSV file handling, crafting functions for header initialization and data row writing. Error handling will also be included in the file interactions to ensure data integrity. I'll use the datetime module for timestamps. Also, I'm thinking about including a console printout as a real-time status indicator.
Detailing Core Metrics and Functions
I'm now zeroing in on the script's core components: the metrics and their collection. I've decided to track CPU utilization, memory usage, and disk space used. For disk, I'll focus on the root partition. The psutil library will provide all of these, and I am structuring functions for each metric to keep it clean.
To perform system monitoring in Python, the standard and most robust library is psutil (Python System and Process Utilities). It provides cross-platform access to system details like CPU, memory, disks, networks, and sensors.
Below is a complete, runnable Python script that monitors these metrics and logs them efficiently to a CSV file. This format allows you to easily open the log later in Excel or load it into data visualization tools.
Prerequisites
You will need to install the psutil library:
bash
pip install psutil
The Python Script (monitor.py)
This script will log specific metrics (CPU usage, RAM usage, Disk usage, and Network traffic) every 5 seconds.
python
How it works:
init_csv_file: It checks if your log file exists. If not, it creates it and adds headers (column names). If it does exist, it simply prepares to append new data to the bottom.
get_system_metrics:
CPU: Uses cpu_percent. We pass interval=1 to sample the CPU for 1 second to get an accurate reading.
Memory: Uses virtual_memory to get the percentage used and available RAM (converted to Megabytes).
Disk: Checks the usage of the root path. (Note: If you are on Windows, you might want to change DISK_PATH to 'C:\\').
Network: Uses net_io_counters to capture total bytes sent/received since the system booted.
Loop & Sleep: The script runs in an infinite while True loop using time.sleep() to pause execution between checks.
KeyboardInterrupt: The try...except block captures Ctrl+C so you can stop the script gracefully without a messy error traceback.
How to visualize the data later:
Since the output is a standard CSV file, you can:
Open it directly in Microsoft Excel or Google Sheets.
Use Python's pandas library to plot graphs:
python
import pandas as pd
import matplotlib.pyplot as plt
# Read the log
df = pd.read_csv('system_monitor_log.csv')
# Convert timestamp to datetime object
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
# Plot CPU and Memory
plt.figure(figsize=(10, 5))
plt.plot(df['Timestamp'], df['CPU_Usage_%'], label='CPU %')
plt.plot(df['Timestamp'], df['Memory_Used_%'], label='Memory %')
plt.legend()
plt.title('System Performance Over Time')
plt.show()
import psutil
import time
import csv
import os
from datetime import datetime
# --- Configuration ---
LOG_FILE = 'system_monitor_log.csv'
LOG_INTERVAL = 5 # Seconds between logs
DISK_PATH = '/' # '/' for Linux/Mac, 'C:\\' for Windows
def init_csv_file(filename):
"""
Initializes the CSV file. Creates it with headers if it doesn't exist.
"""
file_exists = os.path.isfile(filename)
with open(filename, mode='a', newline='') as file:
writer = csv.writer(file)
# Only write headers if the file is new
if not file_exists:
headers = [
'Timestamp',
'CPU_Usage_%',
'Memory_Used_%',
'Memory_Available_MB',
'Disk_Used_%',
'Bytes_Sent',
'Bytes_Recv'
]
writer.writerow(headers)
print(f"Created new log file: {filename}")
else:
print(f"Appending to existing log file: {filename}")
def get_system_metrics():
"""
Gather system metrics using psutil.
"""
# 1. Timestamp
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 2. CPU Usage
# interval=None is non-blocking, but requires a previous call to calculate delta.
# We handle timing in the main loop, so we can use interval=1 here for a 1-sec sample
# or keep it at 0 for instant snapshots.
cpu_usage = psutil.cpu_percent(interval=1)
# 3. Memory (RAM) Usage
memory = psutil.virtual_memory()
mem_usage = memory.percent
mem_available = round(memory.available / (1024 * 1024), 2) # Convert to MB
# 4. Disk Usage
try:
disk = psutil.disk_usage(DISK_PATH)
disk_usage = disk.percent
except Exception as e:
disk_usage = "N/A"
# 5. Network Stats
# This gives total bytes since boot. For bandwidth speed,
# you would need to calculate the difference between two timestamps.
net = psutil.net_io_counters()
bytes_sent = net.bytes_sent
bytes_recv = net.bytes_recv
return [timestamp, cpu_usage, mem_usage, mem_available, disk_usage, bytes_sent, bytes_recv]
def log_metrics(filename, metrics):
"""
Writes the metrics list to the CSV file.
"""
with open(filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow(metrics)
def main():
print("--- System Performance Monitor Started ---")
print(f"Logging to: {LOG_FILE}")
print("Press Ctrl+C to stop.")
init_csv_file(LOG_FILE)
try:
while True:
metrics = get_system_metrics()
# Log to file
log_metrics(LOG_FILE, metrics)
# Optional: Print a summary to console
print(f"[{metrics[0]}] CPU: {metrics[1]}% | Mem: {metrics[2]}% | Disk: {metrics[4]}%")
# Wait for the remaining interval time
# (Note: psutil.cpu_percent(interval=1) already consumed 1 second)
time.sleep(max(0, LOG_INTERVAL - 1))
except KeyboardInterrupt:
print("\n--- Monitoring Stopped by User ---")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
main()