#!/usr/local/bin/perl -w ####################################################################### # Roll Apache Logs ####################################################################### use Time::localtime; use Logfile::Rotate; use File::Basename; $DEBUG = 0; $APACHE_PID_FILE = '/var/run/httpd.pid'; $APACHE_CONF_DIR = '/usr/local/etc/apache24'; $VHOST_CONF_DIR = '/usr/local/etc/apache24/vhosts'; $EXCLUDE_FILE = "$APACHE_CONF_DIR/logroll_exclude.conf"; %Logs = (); $log_count = 0; $aday = 23 * 60 * 60; # a day's worth of seconds $rSecs = time - $aday; $rDate = localtime($rSecs); $logdate = sprintf('%4d%02d%02d', $rDate->year+1900, $rDate->mon+1, $rDate->mday); #### Grep the list of log files out of the vhost configs ############## $log_grep = 'grep -Rhi CustomLog\\\\\\|ErrorLog ' . $VHOST_CONF_DIR; open(LOGS, "$log_grep |") || die("ERROR: Could not get log list: $!\n"); while ( ) { chomp; if ( m/^\s*(Custom|Error)Log\s+(\S+).*$/i ) { $Logs{$2} = 1; $log_count++; } else { print("ERROR: Bad Line: $_\n"); } } close(LOGS); ####################################################################### #### Exclude certain logs ############################################# if (-e $EXCLUDE_FILE) { open(EXCL, "$EXCLUDE_FILE") || die("ERROR: Could not get exclude list: $!\n"); while ( ) { chomp; next if ( m/^\s*$/ ); # skip blank lines next if ( m/^\s*#$/ ); # skip comments if ( m/^\s*(\S+).*$/ ) { delete($Logs{$1}); } } close(EXCL); } ####################################################################### # roll logs foreach my $log ( keys(%Logs) ) { if ( $log =~ m/^(.+)\.(current|today)\.(.+)$/ ) { $newname = "$1.$logdate.$3"; } else { $newname = "$log.$logdate"; } if (-e $log) { if (! -e $newname) { $log_base = basename($log); $new_base = basename($newname); print("Rolling $log_base -> $new_base\n") if ($DEBUG); my $log = new Logfile::Rotate( File => $log, Count => 1, Gzip => 'no', Post => \&BetterName, Flock => 'yes', Persist => 'yes' ); $log->rotate(); undef $log; } else { print STDERR ("Could not rotate $log, file $newname in the way.\n"); } } else { print STDERR ("$log not found, skipping.\n"); } } # Send 'kill' to apache if ( -e $APACHE_PID_FILE ) { open(PID, $APACHE_PID_FILE); chomp($pid = ); kill USR1 => $pid; } else { print STDERR ("Could not signal Apache. Pid file $APACHE_PID_FILE not found"); } ####################################################################### ####################################################################### ####################################################################### sub BetterName { my $old = shift; my $new = shift; rename($new, $main::newname); return 1; }