Apache logs are rotated periodically using logrotate on Linux. By default logrotate was set to rotate my apache logs weekly and this would often occur around ~0620hrs. I would prefer to rotate every Sunday at midnight. This way you separate apache logs by a full week. Note, you may prefer daily if you have a lot of traffic and audit etc. on a daily basis.
Apache logs rotate via the logrotate utility. Although the frequency and parameters of rotating logs with logrotate can be configured to your needs, I wanted to rotate logs precisely every Sunday at midnight. Furthermore, I only wanted this behaviour for my apache logs (and leave other logs being rotated by logrotate). Below outlines changes to force apache log rotation every Sunday at midnight.
We will take the following steps:
- move apache2 logrotation config from the normal logrotate daily cron scripts
- setup an weekly cron job to force execution of apache log rotation script every Sunday at midnight
Move apache2 logrotation config
Since we only want to force apache logs to be rotated every Sunday at midnight, we need to move the apache2 logrotate config files to another folder so that the normal logrotate cron scripts still run as per usual (but not apache log rotations).
To do this we will create a new folder in
/etc and move the apache logrotate conf file
Note that if you're using CentOS or Amazon linux the the file to move will be
Note that since we're moving our apache logrotation config (which we will run directly) it won't inherit the default options defined in /etc/logrotate.conf. Hence we should make sure it contains all the logrotation options we would like. Below is an example of my logrotate.apache file:
Run man logrotate to see descriptions of these logrotate options.
Setup an weekly cron job to execute Apache log rotation script
Now, let's create a cron job to execute the apache log rotation. Simply run:
This will open your crontab file in your system editor (probably vi or nano). If you're using vi, please see here for how to use it.
Below is an example of sudo's crontab after adding a line to execute apache log rotation (see last line):
0 0 * * 0 tells cron to execute it at midnight on Sunday the latter arguments tell logrotate to force rotate your apache logs.
Note that if you're using CentOS or Amazon linux you would use the following arguments instead:
logrotate -f /etc/logrotate.apache/httpd
Testing logrotate scripts
You can test logrotate by running it with the debug flag to see what would happen (in debug mode logs will not actually be rotated):