Introduction
Monitoring system performance is crucial for maintaining a healthy and efficient computing environment. In this guide, we will automate the logging of CPU and memory utilization every 15 minutes using scheduled tasks in Windows and cron jobs in Linux. We will also ensure that a new log file is created daily.
Why This is Useful in Everyday Life
Automating system monitoring can greatly simplify daily operations, especially for developers, system administrators, and IT professionals. Instead of manually checking system resource usage, automated logging allows:
- Early detection of performance issues – Identify spikes in CPU or memory usage before they cause major slowdowns or crashes.
- Efficient troubleshooting – Logs provide historical data, making it easier to diagnose and resolve performance problems.
- Better resource planning – Analyze usage trends over time to optimize system resources.
- Peace of mind – Once set up, the script runs in the background without user intervention, ensuring continuous monitoring.
Setting Up the Python Script
Before setting up the scheduled jobs, let's create a Python script that logs CPU and memory utilization.
Install Required Dependencies
We will use the psutil
module to fetch CPU and memory utilization. If you haven't installed it yet, run:
pip install psutil
Python Script to Log System Utilization
Create a script named system_monitor.py
with the following code:
import psutil
import datetime
import os
def log_system_utilization():
today = datetime.datetime.now().strftime("%Y-%m-%d")
log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, f"cpu_memory_log_{today}.txt")
with open(log_file, "a") as f:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cpu_usage = psutil.cpu_percent(interval=1)
memory_usage = psutil.virtual_memory().percent
log_entry = f"{timestamp} - CPU Usage: {cpu_usage}% | Memory Usage: {memory_usage}%\n"
f.write(log_entry)
print(log_entry)
if __name__ == "__main__":
log_system_utilization()
This script:
- Creates a log directory if it doesn’t exist.
- Generates a new log file daily.
- Logs CPU and memory usage every time it runs.
Scheduling the Script on Linux Using Cron Job
In Linux, we use cron jobs to automate script execution.
Step 1: Open the Crontab Editor
Run the following command:
crontab -e
Step 2: Add the Cron Job
Add the following line at the end of the file to run the script every 15 minutes:
*/15 * * * * /usr/bin/python3 /path/to/system_monitor.py
Explanation:
-
*/15
→ Runs every 15 minutes. -
* * * *
→ Runs every hour, day, month, and weekday. -
/usr/bin/python3
→ Path to the Python interpreter. -
/path/to/system_monitor.py
→ Full path to the script.
Step 3: Save and Exit
Save the file and exit. The cron job will now run every 15 minutes.
Step 4: Verify the Cron Job
To list scheduled cron jobs, run:
crontab -l
Scheduling the Script on Windows Using Task Scheduler
On Windows, we use Task Scheduler to automate the script execution.
Step 1: Open Task Scheduler
Press Win + R
, type taskschd.msc
, and hit Enter.
Step 2: Create a New Task
- Click Create Basic Task.
- Name it "System Utilization Logger" and click Next.
Step 3: Set the Trigger
- Choose Daily and click Next.
- Set the start time to midnight and repeat every day.
- Click Next.
Step 4: Set the Action
- Choose Start a Program and click Next.
- Browse to the Python executable (e.g.,
C:\Python39\python.exe
). - In the Add arguments field, enter the full path to
system_monitor.py
, e.g.:
"C:\path\to\system_monitor.py"
- Click Next and then Finish.
Step 5: Modify Task to Run Every 15 Minutes
- Open Task Scheduler Library, right-click the created task, and select Properties.
- Go to the Triggers tab and click Edit.
- Select Repeat task every 15 minutes and Stop after 1 day.
- Click OK and Apply.
Step 6: Test the Task
Right-click the task and select Run to ensure it executes correctly.
Conclusion
By following this guide, you've successfully automated system monitoring on both Linux and Windows. The script now runs every 15 minutes, generating daily logs to track CPU and memory utilization. This setup helps in proactive system monitoring and can be further enhanced with alert mechanisms or cloud storage integrations.
How This Makes Life Easier
- Saves Time & Effort: No need to manually check system performance.
- Improves System Stability: Prevent unexpected failures by analyzing logs.
- Enhances Troubleshooting: Quickly identify patterns of high CPU/memory usage.
- Scalable & Automated: Works on any system without manual intervention.
With this setup in place, you can focus on other important tasks while ensuring your system's performance is continuously monitored. 🚀
Let me know in the comments if you have any questions or suggestions!
@vikram_patel , @thisaakash , @shreyansh_1904, @karmpatel Thanks for colloborations.
Top comments (1)
Great Work! Keep Going