How to Configure Apache Log Rotation?

This article provides a straightforward, step-by-step guide to setting up and configuring log rotation for the Apache HTTP Server. Managing server logs is critical for maintaining system health, avoiding disk space exhaustion, and ensuring efficient troubleshooting. Below, you will find instructions on utilizing the industry-standard logrotate utility, configuring its settings for Apache, and verifying that your logs are cycling correctly without interrupting web services.

Understanding Apache Log Rotation

Apache continuously records server activity to its access.log and error.log files. Over time, these files can grow to massive sizes, draining disk space and making log analysis nearly impossible. Log rotation solves this by periodically closing the current log file, renaming it (often appending a date), compressing it, and creating a fresh, empty file for new log data.

On most Linux distributions, Apache automatically integrates with logrotate, a powerful system utility designed to automate this exact process.

Step-by-Step Configuration Using logrotate

The configuration for logrotate is managed via text files located in the /etc/logrotate.d/ directory. Apache typically creates its own configuration file there during installation.

1. Open the Apache logrotate Configuration

To view or edit the current rotation settings for Apache, open the configuration file using a text editor with root privileges:

sudo nano /etc/logrotate.d/apache2

(Note: On Red Hat-based systems like CentOS or RHEL, the file is usually named /etc/logrotate.d/httpd.)

2. Define the Rotation Rules

Inside the file, you will see a block of code defining how the logs should be handled. A standard, optimized configuration looks like this:

/var/log/apache2/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        if invoke-rc.d apache2 status > /dev/null 2>&1; then \
            invoke-rc.d apache2 reload > /dev/null 2>&1; \
        fi;
    endscript
}

3. Key Configuration Parameters Explained

To customize how your logs are handled, adjust the following parameters inside the configuration block:

Testing Your Configuration

After saving your changes, you can verify that the configuration is syntactically correct and simulate a log rotation. Run the following command to force a dry run:

sudo logrotate -df /etc/logrotate.d/apache2

The -d (debug) flag prints out exactly what logrotate would do without actually modifying any files, allowing you to catch errors before they impact your live production environment.