Developing a Python script
The user wants a Python script to monitor system performance metrics, but there are some unclear details about the environment, metrics to log, and log destination. I think using the psutil library is a good approach to log CPU, memory, disk, network, and possibly GPU metrics. I want to keep it concise but helpful, ensuring not too much verbosity. I can design a general script that logs to a file with timestamps, with some configuration options at the top. I'll also include installation requirements and usage instructions.Designing performance monitoring script
For the user request, I want to create a concise script that logs system performance metrics, avoiding lengthy explanations but including helpful commentary in the code. I’ll ensure it’s a single-file solution and include signal handling for a clean exit, which can be done with Ctrl+C. I’ll mention that psutil can be installed via pip and keep external dependencies minimal. The log will be structured as CSV, tracking columns like timestamp, CPU usage, memory, and disk space, while also calculating network throughput between intervals. I’ll implement a function to collect these metrics and return them as a dictionary.Implementing metrics logging
I’m thinking about how to implement the script to monitor system performance metrics effectively. I’ll maintain a variable for previous network data to compute rates, but during the first iteration, I’ll set fields to 0 or None. The log file should be CSV with headers, and I’ll use the csv module to ensure it's created if it doesn't exist. I might add optional command-line arguments for things like interval and log file path, but keeping it basic seems essential for the user.
The code will include functions to parse arguments, get metrics, ensure the log file, and a main function to handle everything.Implementing the metrics loop
I’m drafting the main loop for the performance monitoring script now. The plan is to call get_metrics and write the results to the log, ensuring we use time.sleep after measurements to avoid any issues. However, I need to be careful with how we handle the elapsed time, particularly for network rate calculations. By using a monotonic timer, I can accurately measure the time since the last measurement, allowing for reliable calculations of network rates.
So, in my while loop, I’ll implement a structure where I calculate the metrics, write the output, and manage timing effectively to ensure we don’t have drift issues.Drafting a simplified monitoring script
I'm looking to create a user-friendly system performance monitor that logs CPU, memory, and disk usage into a CSV file. Given the novice audience, I'll keep it straightforward, primarily using psutil and logging to a CSV without complex explanations. I'll design the script with an appropriate docstring, mention the installation of psutil, and include an example of how to run it.
In the main loop, I plan to call collect_metrics for logging, handle keyboard interrupts gracefully, and ensure that the script works cross-platform by accounting for disk usage paths correctly. I'll also avoid overcomplicating it while noting that production-level code might need more features, like log rotation. Here’s a self-contained Python script that periodically logs system performance metrics (CPU, memory, disk, network) to a CSV file.
It uses the psutil library, which is cross-platform (Linux/Windows/macOS).
1. Install dependency
pip install psutil
2. Script: system_monitor.py
#!/usr/bin/env python3
"""
Simple system performance monitor.
Logs CPU, memory, disk, and network usage to a CSV file at a fixed interval.
Usage:
python system_monitor.py --interval 5 --log-file system_metrics.csv
Requires:
pip install psutil
"""
import argparse
import csv
import os
import time
from datetime import datetime
import psutil
def parse_args():
parser = argparse.ArgumentParser(description="Monitor and log system performance metrics.")
parser.add_argument(
"--interval",
type=float,
default=5.0,
help="Sampling interval in seconds (default: 5.0)",
)
parser.add_argument(
"--log-file",
type=str,
default="system_metrics.csv",
help="Path to CSV log file (default: system_metrics.csv)",
)
return parser.parse_args()
def collect_metrics(prev_net=None, prev_time=None):
"""
Collect system performance metrics.
prev_net: previous psutil.net_io_counters() result (or None)
prev_time: timestamp (time.time()) of previous sample (or None)
Returns:
metrics (dict), current_net (psutil._common.snetio), current_time (float)
"""
now = time.time()
dt = (now - prev_time) if prev_time is not None else None
# Timestamp in ISO 8601 (UTC)
timestamp = datetime.utcnow().isoformat()
# CPU (%)
cpu_percent = psutil.cpu_percent(interval=None)
# Memory
mem = psutil.virtual_memory()
mem_used_mb = mem.used / (1024 ** 2)
mem_available_mb = mem.available / (1024 ** 2)
# Disk (root filesystem)
root_path = os.path.abspath(os.sep)
disk = psutil.disk_usage(root_path)
disk_used_gb = disk.used / (1024 ** 3)
disk_free_gb = disk.free / (1024 ** 3)
# Network (bytes and rates)
net = psutil.net_io_counters()
if prev_net is not None and dt and dt > 0:
bytes_sent_rate = (net.bytes_sent - prev_net.bytes_sent) / dt
bytes_recv_rate = (net.bytes_recv - prev_net.bytes_recv) / dt
else:
bytes_sent_rate = 0.0
bytes_recv_rate = 0.0
# Convert rates to kilobits per second (kbps)
sent_kbps = bytes_sent_rate * 8 / 1024
recv_kbps = bytes_recv_rate * 8 / 1024
metrics = {
"timestamp_utc": timestamp,
"cpu_percent": round(cpu_percent, 2),
"mem_used_mb": round(mem_used_mb, 2),
"mem_available_mb": round(mem_available_mb, 2),
"mem_percent": round(mem.percent, 2),
"disk_used_gb": round(disk_used_gb, 2),
"disk_free_gb": round(disk_free_gb, 2),
"disk_percent": round(disk.percent, 2),
"net_bytes_sent": net.bytes_sent,
"net_bytes_recv": net.bytes_recv,
"net_sent_kbps": round(sent_kbps, 2),
"net_recv_kbps": round(recv_kbps, 2),
}
return metrics, net, now
def main():
args = parse_args()
log_file = args.log_file
interval = args.interval
# Do an initial sample (network rate will be 0 for this row)
metrics, prev_net, prev_time = collect_metrics()
# Check if file exists to decide whether to write header
file_exists = os.path.exists(log_file)
with open(log_file, mode="a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(metrics.keys()))
if not file_exists:
writer.writeheader()
# Write initial row
writer.writerow(metrics)
f.flush()
print(f"Logging system metrics every {interval} seconds to: {log_file}")
print("Press Ctrl+C to stop.")
try:
while True:
time.sleep(interval)
metrics, prev_net, prev_time = collect_metrics(prev_net, prev_time)
writer.writerow(metrics)
f.flush()
except KeyboardInterrupt:
print("\nMonitoring stopped.")
if __name__ == "__main__":
main()
3. How to run
python system_monitor.py --interval 5 --log-file system_metrics.csv
--interval: sampling interval in seconds (default 5.0)
--log-file: path to output CSV file
The CSV will contain columns like:
timestamp_utc
cpu_percent
mem_used_mb, mem_available_mb, mem_percent
disk_used_gb, disk_free_gb, disk_percent
net_bytes_sent, net_bytes_recv
net_sent_kbps, net_recv_kbps
If you tell me your OS and any specific metrics or format (JSON, log rotation, daemon/service, etc.), I can tailor this further.