roll_apache_logs/roll_apache_logs.pl

125 lines
2.8 KiB
Perl
Raw Normal View History

2020-12-01 10:58:30 -08:00
#!/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';
2020-12-01 11:13:26 -08:00
$VHOST_CONF_DIR = '/usr/local/etc/apache24/vhosts';
2020-12-01 10:58:30 -08:00
$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 (<LOGS> ) {
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 (<EXCL> ) {
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 = <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;
}