Implementing Log Rotation and Retention

Implementing Log Rotation and Retention

Proper log rotation prevents disk space exhaustion while maintaining necessary history:

# Apache logrotate configuration
sudo cat > /etc/logrotate.d/apache2-security << EOF
/var/log/apache2/*.log {
    daily
    missingok
    rotate 90
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /usr/bin/systemctl reload apache2 > /dev/null 2>&1 || true
    endscript
    dateext
    dateformat -%Y%m%d
    
    # Security: Set immutable flag on rotated logs
    lastaction
        /usr/bin/chattr +a /var/log/apache2/*.log-* 2>/dev/null || true
    endscript
}

/var/log/apache2/modsec_audit.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /usr/bin/systemctl reload apache2 > /dev/null 2>&1 || true
    endscript
}
EOF

# Nginx logrotate configuration
sudo cat > /etc/logrotate.d/nginx-security << EOF
/var/log/nginx/*.log {
    daily
    missingok
    rotate 90
    compress
    delaycompress
    notifempty
    create 640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 \`cat /var/run/nginx.pid\`
    endscript
    dateext
    dateformat -%Y%m%d
    
    # Security: Set immutable flag
    lastaction
        /usr/bin/chattr +a /var/log/nginx/*.log-* 2>/dev/null || true
    endscript
}

/var/log/nginx/security.json {
    daily
    rotate 180
    compress
    delaycompress
    missingok
    notifempty
    create 640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 \`cat /var/run/nginx.pid\`
    endscript
}
EOF

# Test logrotate configuration
sudo logrotate -d /etc/logrotate.d/apache2-security
sudo logrotate -d /etc/logrotate.d/nginx-security