Managing a macOS environment, whether on a personal Mac or within an enterprise fleet, inevitably leads to disk space constraints caused by accumulating log files. Without intervention, logs from services like Web Server (Apache/Nginx), databases, and system daemons can grow indefinitely, degrading performance and potentially causing the system to become unresponsive. The industry-standard solution is automated log rotation using cron jobs. This guide provides a concrete, step-by-step approach to writing secure cron jobs for log rotation on macOS, moving beyond manual deletion to a robust maintenance strategy suitable for IT students and junior engineers.
Understanding the Risks of Unmanaged Logs
Before writing any automation script, it is crucial to understand what you are managing. macOS uses the /var/log directory to store system logs (e.g., system.log, auth.log) and application-specific logs. While modern macOS versions include a built-in log rotation mechanism via LaunchDaemons, this often does not cover third-party applications or specific development environments (like local Node.js servers or Docker containers) that generate massive output files.
If left unchecked, a single log file can consume gigabytes of space. In a workplace scenario, imagine a developer running a high-traffic local web server for testing. Without rotation, the access logs could fill the disk within 24 hours, causing the Mac to fail booting or preventing users from saving new data. Automating this process ensures that old logs are archived or compressed before they reach critical thresholds.
Prerequisites and Environment Setup
To follow this guide, you will need a standard macOS installation (Intel or Apple Silicon) with administrative privileges. You must be logged in as a user with sudo access to create the necessary scripts and modify system cron files.
Ensure your Terminal is up to date. While no specific OS version is mandated, the commands used here are compatible with macOS Monterey through Sonoma and later. If you are working in a lab environment, ensure you have at least 10GB of free space to simulate log growth during testing. It is highly recommended to create a dedicated directory for your rotation scripts to keep the system organized:
mkdir -p ~/bin/logrotate
chmod +x ~/bin/logrotate
Creating the Rotation Script
The core of your automation is a shell script that performs the actual rotation. We will use standard Unix tools like gzip for compression and mv for renaming, avoiding complex third-party utilities to ensure compatibility.
Create a new file named rotate_logs.sh in your ~/bin/logrotate directory. The following script handles rotating logs for a hypothetical application located at /var/log/myapp/app.log. It checks the file size; if it exceeds 50MB (52428800 bytes), it compresses the current log, renames it with a timestamp, and creates a new empty log file.
#!/bin/bash
# Configuration Variables
LOG_FILE="/var/log/myapp/app.log"
MAX_SIZE=52428800 # 50MB in bytes
ARCHIVE_DIR="/var/log/myapp/archive"
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
# Safety Check: Ensure the log directory exists
if [ ! -d "$(dirname "$LOG_FILE")" ]; then
echo "Error: Log directory does not exist."
exit 1
fi
# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR"
# Check file size
if [ -f "$LOG_FILE" ] && [ $(stat -f%z "$LOG_FILE") -gt $MAX_SIZE ]; then
# Compress the old log
gzip -c "$LOG_FILE" > "$ARCHIVE_DIR/app.log.${TIMESTAMP}.gz"
# Truncate the original log to free up space immediately
> "$LOG_FILE"
echo "Rotated: $(basename $LOG_FILE) -> ${ARCHIVE_DIR}/app.log.${TIMESTAMP}.gz"
else
echo "Log file is under threshold ($MAX_SIZE bytes). No action needed."
fi
Explanation of the Code:
* #!/bin/bash: Sets the interpreter.
* stat -f%z: Retrieves the file size on macOS (using -f for BSD syntax). On Linux, this would be stat -c%s.
* gzip -c: Reads from stdin and writes compressed output to a file, preserving the original source until the redirect completes.
* > "$LOG_FILE": Truncates the file. This is safer than deleting it, as it keeps the inode intact for applications writing to it continuously.
Scheduling the Job with Cron
Once the script is created, you must schedule it to run automatically. macOS uses the standard Unix cron daemon, located at /var/spool/cron on Intel Macs or managed via launchd on Apple Silicon (though cron remains available for compatibility).
- Open the crontab editor:
bash
sudo crontab -e - Add the following line to run the script every day at 3:00 AM:
cron
0 3 * * * /Users/YOUR_USERNAME/bin/logrotate/rotate_logs.sh >> /var/log/cron_rotate.log 2>&1
Note on Paths: Replace YOUR_USERNAME with your actual short username. Using absolute paths in cron jobs prevents issues if the environment variables differ when the job runs compared to an interactive session. The output is redirected to a log file to help with troubleshooting.
Verification and Expected Results
After saving the crontab, verify that the job was added correctly by listing the current schedule:
crontab -l
To test the automation immediately without waiting for 3 AM, you can manually execute the script or simulate a large log file. Run the script directly:
/Users/YOUR_USERNAME/bin/logrotate/rotate_logs.sh
Expected Output:
If the log is large enough, you should see: Rotated: app.log -> /var/log/myapp/archive/app.log.YYYY-MM-DD_HH-MM-SS.gz. If the log is small, it will state that no action was needed. Check the disk usage before and after to confirm space reclamation.
Common Errors and Fixes
When setting up cron jobs on macOS, several specific errors frequently occur:
- Permission Denied: If you receive a permission error when running the script via cron, ensure the script file has execute permissions (
chmod +x /path/to/script) and that it does not rely on interactive prompts (likereadcommands) which block non-interactive cron jobs. - Path Resolution Issues: Cron runs with a minimal environment. If your script relies on
which pythonor other dynamic path lookups, they may fail. Always use absolute paths in the script itself. - Race Conditions: If an application is actively writing to the log file while it is being compressed, you might encounter “text file busy” errors. The truncation step (
> "$LOG_FILE") must happen after compression but be careful if the application opens the file for exclusive write access. A robust solution involves usinglogrotate‘s built-in mechanisms or ensuring the application flushes buffers before rotation, though simple truncation is often sufficient for text-based logs.
Student Practice Task
To solidify your understanding, students should perform the following lab exercise:
1. Create a test directory /tmp/test_logs.
2. Write a script that rotates any .txt file in that directory once it exceeds 1MB.
3. Schedule this script to run every hour using cron.
4. Create a loop in Terminal that generates a 500KB random text file every 10 seconds, simulating log generation.
5. Observe the disk usage graph in Activity Monitor over a 2-hour period to verify that disk space remains stable despite continuous writing.
Industry Application and Best Practices
In a professional setting, this automation is part of a broader DevOps or SRE (Site Reliability Engineering) strategy. While macOS often handles system logs well, application-level logs require custom handling. It is best practice to include log rotation in your infrastructure-as-code templates (like Ansible playbooks or configuration management scripts) rather than hard-coding cron jobs manually.
Always verify policy terms if this is part of a corporate compliance requirement regarding data retention. For instance, a company policy might dictate that logs older than 90 days must be deleted. You can modify your script to include a cleanup step:
# Remove archives older than 90 days
find "$ARCHIVE_DIR" -name "*.gz" -mtime +90 -delete
Remember that terms, availability, and specific retention laws depend on the jurisdiction and the specific organizational policy. Always consult your organization’s IT security team before automating data deletion to ensure compliance with legal requirements such as GDPR or CCPA. By mastering these steps, you ensure a stable, efficient macOS environment capable of handling heavy workloads without manual intervention.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

