1. Home
  2. Computing & Technology
  3. Perl

Log Rotation - How to rotate your server log files with Perl

Rotating the access log

By Kirk Brown, About.com

Next: Rotating the error log

In order to rotate our access logs, first lets setup three filenames. $access_file should be the name of your actual Apache log access file. This is typically something along the lines of mywebsite.com-access_log, but double check with your configuration files first. We're going to be renaming this file every night with the current date, so let's create $access_archivefile using strftime to add the date. Finally, we define $access_archivezip in the same way (stamped with the date) adding the .tar.gz to the end.

$access_file = "mywebsite.com-access_log";
$access_archivefile = strftime("$access_file.%Y-%m-%d", localtime);
$access_archivezip = "$access_archivefile.tar.gz";
Now it's time to get the job done using the system function. First we move the original file to the new archive name (which will temporarily stop the web server writing it's logs). Next step is to tar and zip the file and create the actual archive zip file.
system "mv $access_file $access_archivefile";
system "tar -czf $access_archivezip $access_archivefile";
Next, let's delete the un-zipped archive file and mv the zipped one on into the archives directory.
system "rm $access_archivefile";
system "mv $access_archivezip archives/";
Next: Rotating the error log

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Log Rotation - How to rotate your server log files with Perl

©2008 About.com, a part of The New York Times Company.

All rights reserved.