Configure Linux log rotation with logrotate and compression for system maintenance

Intermediate 25 min Apr 03, 2026 32 views
Ubuntu 24.04 Ubuntu 22.04 Debian 12 AlmaLinux 9 Rocky Linux 9 Fedora 41

Master log rotation with logrotate to manage disk space efficiently. Configure custom rotation policies, compression settings, and automated cleanup for applications and system logs.

Prerequisites

  • Root or sudo access
  • Basic understanding of Linux file permissions
  • Email server configured (optional for notifications)

What this solves

Log files can consume enormous amounts of disk space without proper rotation, potentially causing system outages when storage fills up. This tutorial shows you how to configure logrotate to automatically compress, rotate, and clean up logs based on size, age, and custom policies, ensuring your servers maintain optimal performance and storage availability.

Step-by-step configuration

Install logrotate package

Most Linux distributions include logrotate by default, but verify it's installed and up to date.

sudo apt update
sudo apt install -y logrotate
sudo dnf update -y
sudo dnf install -y logrotate

Verify logrotate installation and status

Check that logrotate is properly installed and review the main configuration file structure.

logrotate --version
ls -la /etc/logrotate.conf
ls -la /etc/logrotate.d/

Configure global logrotate settings

Edit the main configuration file to set default rotation policies that apply to all logs unless overridden.

# Global settings for log rotation
weekly
rotate 4
create
dateext
compress
delaycompress

Include application-specific configurations

include /etc/logrotate.d

System logs configuration

/var/log/wtmp { monthly create 0664 root utmp minsize 1M rotate 1 } /var/log/btmp { missingok monthly create 0600 root utmp rotate 1 }

Create custom application log rotation

Configure rotation for web server logs with compression and size-based rotation to prevent disk space issues.

/var/log/webapp/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0644 webapp webapp
    size 100M
    maxage 90
    postrotate
        systemctl reload webapp 2>/dev/null || true
    endscript
}

Configure system service log rotation

Set up rotation for system services like nginx with proper permissions and reload commands.

/var/log/nginx/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 0640 www-data adm
    size 50M
    maxage 30
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi
    endscript
    postrotate
        if [ -f /var/run/nginx.pid ]; then \
            kill -USR1 cat /var/run/nginx.pid; \
        fi
    endscript
}

Configure database log rotation with compression

Set up MySQL/MariaDB log rotation with proper ownership and compression settings.

/var/log/mysql/*.log {
    weekly
    rotate 8
    compress
    delaycompress
    missingok
    notifempty
    create 0640 mysql mysql
    copytruncate
    maxage 56
    postrotate
        systemctl reload mysql 2>/dev/null || true
    endscript
}

/var/log/mysql/error.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0640 mysql mysql
    size 10M
    maxage 14
}

Set up email notifications for rotation failures

Configure logrotate to send email alerts when rotation fails, helping you catch issues before they cause outages.

sudo apt install -y mailutils postfix
sudo dnf install -y mailx postfix
# Add to top of /etc/logrotate.conf
mail admin@example.com
mailfirst

Create disk space monitoring script

Set up automated disk usage monitoring to complement log rotation and prevent storage issues.

#!/bin/bash

Disk space monitoring script for log directories

THRESHOLD=80 EMAIL="admin@example.com" check_disk_usage() { local path="$1" local usage=$(df "$path" | tail -1 | awk '{print $5}' | sed 's/%//') if [ "$usage" -gt "$THRESHOLD" ]; then echo "WARNING: Disk usage for $path is ${usage}%" | \ mail -s "High Disk Usage Alert - $(hostname)" "$EMAIL" fi }

Monitor critical log directories

check_disk_usage "/var/log" check_disk_usage "/var/log/nginx" check_disk_usage "/var/log/mysql"

Force logrotate if disk usage is critical (>90%)

for dir in /var/log /var/log/nginx /var/log/mysql; do usage=$(df "$dir" | tail -1 | awk '{print $5}' | sed 's/%//') if [ "$usage" -gt 90 ]; then /usr/sbin/logrotate -f /etc/logrotate.conf echo "Emergency logrotate executed for high disk usage" | \ mail -s "Emergency Log Rotation - $(hostname)" "$EMAIL" fi done
sudo chmod 755 /usr/local/bin/check-disk-space.sh

Schedule automated monitoring and rotation

Set up cron jobs to run logrotate and disk monitoring automatically.

sudo crontab -e
# Run logrotate daily at 2 AM
0 2   * /usr/sbin/logrotate /etc/logrotate.conf

Check disk space every 4 hours

0 /4 /usr/local/bin/check-disk-space.sh

Weekly cleanup of old compressed logs

0 3 0 find /var/log -name "*.gz" -mtime +90 -delete

Configure logrotate status tracking

Set up proper status file permissions and monitoring for logrotate execution history.

sudo touch /var/lib/logrotate/status
sudo chmod 644 /var/lib/logrotate/status
sudo chown root:root /var/lib/logrotate/status

Test rotation configuration

Perform a dry run to verify your configuration works correctly before relying on automated rotation.

# Test configuration syntax
sudo logrotate -d /etc/logrotate.conf

Force rotation for testing (creates actual rotated files)

sudo logrotate -f /etc/logrotate.conf

Test specific configuration

sudo logrotate -d /etc/logrotate.d/nginx

Advanced compression and retention settings

Configure different compression methods

Optimize compression settings for different log types to balance CPU usage and space savings.

# High compression for infrequently accessed logs
/var/log/archive/*.log {
    monthly
    rotate 12
    compress
    compresscmd /usr/bin/xz
    uncompresscmd /usr/bin/unxz
    compressext .xz
    compressoptions -9
    delaycompress
    create 0644 root root
}

Fast compression for frequently rotated logs

/var/log/highvolume/*.log { hourly rotate 168 compress compresscmd /usr/bin/gzip compressoptions -1 delaycompress size 1G create 0644 app app }

Set up conditional rotation based on system load

Create intelligent rotation that considers system resources to avoid impacting performance during peak times.

/var/log/conditional/*.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
    create 0644 app app
    prerotate
        # Skip rotation if system load is too high
        load=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
        if (( $(echo "$load > 5.0" | bc -l) )); then
            echo "Skipping rotation due to high system load: $load"
            exit 1
        fi
    endscript
    postrotate
        systemctl reload app 2>/dev/null || true
    endscript
}

Verify your setup

# Check logrotate service status
sudo systemctl status logrotate.timer

Verify configuration files

sudo logrotate -d /etc/logrotate.conf

Check rotation status

sudo cat /var/lib/logrotate/status

Monitor disk usage

df -h /var/log

List rotated and compressed logs

find /var/log -name ".gz" -o -name ".xz" | head -10

Check cron job status

sudo grep logrotate /var/log/cron

Monitor rotation effectiveness

# Create monitoring script for rotation metrics
cat > /usr/local/bin/logrotate-stats.sh << 'EOF'
#!/bin/bash
echo "=== Log Rotation Statistics ==="
echo "Total log files: $(find /var/log -name "*.log" | wc -l)"
echo "Compressed files: $(find /var/log -name ".gz" -o -name ".xz" | wc -l)"
echo "Disk usage: $(du -sh /var/log | awk '{print $1}')"
echo "Last rotation: $(stat -c %y /var/lib/logrotate/status)"
echo "Rotation errors: $(grep -c ERROR /var/log/logrotate.log 2>/dev/null || echo 0)"
EOF

sudo chmod +x /usr/local/bin/logrotate-stats.sh
/usr/local/bin/logrotate-stats.sh

Common issues

SymptomCauseFix
Files not rotatingIncorrect permissions on log filessudo chown root:root /etc/logrotate.d/* and check log file ownership
Compression failsMissing compression utilitiesInstall gzip/xz: sudo apt install gzip xz-utils (Ubuntu) or sudo dnf install gzip xz (RHEL)
Service reload failsInvalid postrotate commandTest commands manually and use || true to prevent failures
Email notifications not workingMail system not configuredConfigure postfix: sudo dpkg-reconfigure postfix
Logs still consuming spaceApplication writing to rotated filesUse copytruncate option or ensure proper service reload
Permission denied errorsLogrotate running as wrong userCheck cron runs as root and log directories have correct permissions
Never use chmod 777. It gives every user on the system full access to your log files. Instead, set specific ownership with chown and use minimal permissions like 644 for log files and 755 for log directories.

Next steps

Automated install script

Run this to automate the entire setup

#logrotate #log rotation #compression #disk management #system maintenance

Need help?

Don't want to manage this yourself?

We handle infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.

Talk to an engineer