System Performance Tracker Script
This script utilizes Python's psutil library to track system performance metrics such as CPU usage, memory, and disk space. It provides a simple and efficient way to monitor system resources.
Prerequisites
- Python 3.6+
psutil library (install using pip install psutil)
Script
import psutil
import time
import platform
import logging
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def get_size(bytes):
"""
Returns size of bytes in a nice format
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P']:
if bytes < 1024:
return f"{bytes:.2f}{unit}B"
bytes /= 1024
def get_system_info():
"""
Returns system information
"""
info = {}
info['platform'] = platform.system()
info['platform-release'] = platform.release()
info['platform-version'] = platform.version()
info['architecture'] = platform.machine()
info['processor'] = platform.processor()
return info
def get_cpu_info():
"""
Returns CPU information
"""
info = {}
info['physical cores'] = psutil.cpu_count(logical=False)
info['total cores'] = psutil.cpu_count(logical=True)
info['current frequency'] = f"{psutil.cpu_freq().current / 1000:.2f} GHz"
info['max frequency'] = f"{psutil.cpu_freq().max / 1000:.2f} GHz"
info['min frequency'] = f"{psutil.cpu_freq().min / 1000:.2f} GHz"
info['cpu usage per core'] = []
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
info['cpu usage per core'].append(f"Core {i}: {percentage}%")
info['total cpu usage'] = f"{psutil.cpu_percent()}%"
return info
def get_memory_info():
"""
Returns memory information
"""
info = {}
svmem = psutil.virtual_memory()
info['total memory'] = get_size(svmem.total)
info['available memory'] = get_size(svmem.available)
info['used memory'] = get_size(svmem.used)
info['percentage'] = f"{svmem.percent}%"
return info
def get_disk_info():
"""
Returns disk information
"""
info = {}
info['total read'] = get_size(psutil.disk_io_counters().read_bytes)
info['total write'] = get_size(psutil.disk_io_counters().write_bytes)
partitions = psutil.disk_partitions()
for partition in partitions:
info[f"=== Device: {partition.device} ==="] = ""
info[f" Mountpoint: {partition.mountpoint}"] = ""
info[f" File system type: {partition.fstype}"] = ""
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
except PermissionError:
continue
info[f" Total Size: {get_size(partition_usage.total)}"] = ""
info[f" Used: {get_size(partition_usage.used)}"] = ""
info[f" Free: {get_size(partition_usage.free)}"] = ""
info[f" Percentage: {partition_usage.percent}%"] = ""
return info
def track_performance(interval=1):
"""
Tracks system performance metrics
"""
try:
while True:
# System Info
logging.info("System Information:")
system_info = get_system_info()
for key, value in system_info.items():
logging.info(f" {key}: {value}")
# CPU Info
logging.info("\nCPU Information:")
cpu_info = get_cpu_info()
for key, value in cpu_info.items():
if isinstance(value, list):
for item in value:
logging.info(f" {item}")
else:
logging.info(f" {key}: {value}")
# Memory Info
logging.info("\nMemory Information:")
memory_info = get_memory_info()
for key, value in memory_info.items():
logging.info(f" {key}: {value}")
# Disk Info
logging.info("\nDisk Information:")
disk_info = get_disk_info()
for key, value in disk_info.items():
logging.info(f" {key}{value}")
logging.info("\n" + "="*40 + "\n")
time.sleep(interval)
except KeyboardInterrupt:
logging.info("Stopping performance tracking...")
if __name__ == "__main__":
track_performance(interval=5) # Track performance every 5 seconds
How it Works
- The script starts by importing the necessary libraries:
psutil for system performance metrics, time for intervals, platform for system information, and logging for logging messages.
- The
get_size function formats bytes into a human-readable format (e.g., KB, MB, GB).
- The
get_system_info, get_cpu_info, get_memory_info, and get_disk_info functions retrieve system, CPU, memory, and disk information using psutil and platform.
- The
track_performance function runs an infinite loop, logging system performance metrics at specified intervals (default: 1 second).
- Press
Ctrl+C to stop the performance tracking.
Example Output
2023-12-01 12:00:00,000 - INFO - System Information:
2023-12-01 12:00:00,000 - INFO - platform: Linux
2023-12-01 12:00:00,000 - INFO - platform-release: 5.11.0-27-generic
2023-12-01 12:00:00,000 - INFO - platform-version: #29~20.04.1-Ubuntu SMP Wed Aug 11 15:58:17 UTC 2021
2023-12-01 12:00:00,000 - INFO - architecture: x86_64
2023-12-01 12:00:00,000 - INFO - processor: x86_64
2023-12-01 12:00:01,000 - INFO -
CPU Information:
2023-12-01 12:00:01,000 - INFO - physical cores: 4
2023-12-01 12:00:01,000 - INFO - total cores: 8
2023-12-01 12:00:01,000 - INFO - current frequency: 2.50 GHz
2023-12-01 12:00:01,000 - INFO - max frequency: 3.20 GHz
2023-12-01 12:00:01,000 - INFO - min frequency: 0.80 GHz
2023-12-01 12:00:02,000 - INFO - Core 0: 10.0%
2023-12-01 12:00:02,000 - INFO - Core 1: 5.0%
2023-12-01 12:00:02,000 - INFO - Core 2: 8.0%
2023-12-01 12:00:02,000 - INFO - Core 3: 12.0%
2023-12-01 12:00:02,000 - INFO - Core 4: 6.0%
2023-12-01 12:00:02,000 - INFO - Core 5: 9.0%
2023-12-01 12:00:02,000 - INFO - Core 6: 7.0%
2023-12-01 12:00:02,000 - INFO - Core 7: 11.0%
2023-12-01 12:00:02,000 - INFO - total cpu usage: 8.5%
2023-12-01 12:00:02,000 - INFO -
Memory Information:
2023-12-01 12:00:02,000 - INFO - total memory: 15.62GB
2023-12-01 12:00:02,000 - INFO - available memory: 8.12GB
2023-12-01 12:00:02,000 - INFO - used memory: 7.50GB
2023-12-01 12:00:02,000 - INFO - percentage: 48.0%
2023-12-01 12:00:02,000 - INFO -
Disk Information:
2023-12-01 12:00:02,000 - INFO - total read: 10.23GB
2023-12-01 12:00:02,000 - INFO - total write: 5.67GB
2023-12-01 12:00:02,000 - INFO - === Device: /dev/sda2 ===
2023-12-01 12:00:02,000 - INFO - Mountpoint: /
2023-12-01 12:00:02,000 - INFO - File system type: ext4
2023-12-01 12:00:02,000 - INFO - Total Size: 243.94GB
2023-12-01 12:00:02,000 - INFO - Used: 145.21GB
2023-12-01 12:00:02,000 - INFO - Free: 98.73GB
2023-12-01 12:00:02,000 - INFO - Percentage: 59.5%
2023-12-01 12:00:02,000 - INFO - ========================================
Tips and Variations
- Adjust the
interval parameter in track_performance to change the logging frequency.
- Modify the logging level by changing
logging.basicConfig(level=logging.INFO, ...) to logging.basicConfig(level=logging.DEBUG, ...), for example, to see more detailed information.
- Use this script as a starting point and add more metrics or features as needed (e.g., network usage, process monitoring).
- Consider integrating this script with a dashboarding tool like Grafana or a logging platform like ELK Stack for visualization and centralized logging.