Installing sysstat Package
To use cpustat for logging CPU statistics, you must first install the sysstat package, which includes cpustat and other system monitoring tools. Run the following commands to update your package list and install sysstat:
sudo apt update sudo apt install sysstat This installs the necessary components to enable CPU usage logging.
Method 1: Manual Real-Time Logging with Output Redirection
The simplest way to log cpustat output is by redirecting its output to a file. Use the -o option to specify the log file path or standard redirection (> for overwriting, >> for appending). For example, to log CPU usage every second indefinitely (press Ctrl+C to stop):
sudo cpustat -o /var/log/cpu_usage.log 1 Or, to append data every second to a file without overwriting:
sudo cpustat -u 1 >> /var/log/cpu_usage.log Here, -u displays user/system/idle time percentages, and 1 sets the sampling interval (in seconds). Adjust the interval as needed.
Method 2: Automated Periodic Logging with Cron
For scheduled logging (e.g., every 5 minutes), create a cron job. Edit the current user’s crontab with:
crontab -e Add the following line to run cpustat every 5 minutes and append output to /var/log/cpu_usage.log:
*/5 * * * * sudo cpustat -u 1 >> /var/log/cpu_usage.log Save and exit the editor. The cron daemon will execute the command at the specified intervals.
Method 3: Script-Based Logging with Timestamps
For more structured logs (including timestamps), create a bash script. For example, create /usr/local/bin/log_cpu_usage.sh with:
#!/bin/bash LOG_FILE="/var/log/cpu_usage.log" while true; do TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S') echo "[$TIMESTAMP] CPU Usage:" >> "$LOG_FILE" cpustat -u 1 1 >> "$LOG_FILE" sleep 60 # Log every minute done Make the script executable and run it with root privileges:
sudo chmod +x /usr/local/bin/log_cpu_usage.sh sudo /usr/local/bin/log_cpu_usage.sh This script appends a timestamp and 1-second CPU sample to the log file every minute. To stop it, use Ctrl+C in the terminal where it’s running.
Viewing Logged Data
To view the log file, use text editors or command-line tools. For example:
sudo less /var/log/cpu_usage.log # Paginated view sudo tail -f /var/log/cpu_usage.log # Real-time updates If using sysstat’s built-in logging (via sar), check historical data in /var/log/sysstat/saXX (where XX is the day of the month). Use cpustat -r /var/log/sysstat/saXX to view specific dates.
Stopping the Logging Process
Ctrl+C in the terminal.crontab -e).ps aux | grep log_cpu_usage.sh and kill it with sudo kill <PID>.