Skip to content

Instantly share code, notes, and snippets.

@cosmomill
Created February 1, 2013 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosmomill/4693222 to your computer and use it in GitHub Desktop.
Save cosmomill/4693222 to your computer and use it in GitHub Desktop.
Purge cronolog logfiles. ErrorLog "|/usr/bin/cronolog -r /usr/bin/cronopurge -G '1week:/var/log/apache2/error.log.%s' -p 12hour -l /var/log/apache2/error.log /var/log/apache2/error.log.%s"
#!/usr/bin/perl
#
# Author: Nicolas Mendoza <nicolasm@opera.com> 2011
use strict;
use warnings;
use Data::Dumper;
use File::Basename;
use File::stat;
use File::Spec;
use Time::localtime;
use Regexp::Common qw(time);
my $DEBUG = 0;
my $NO_ACT = 0;
my ($maxage, $logfile_spec) = split m{:}, (shift || q{});
my $logfile = shift;
usage() unless (defined $maxage && defined $logfile_spec && defined $logfile);
my $logdir = dirname($logfile_spec);
my $logfile_pattern = $RE{time}{strftime}{-pat => $logfile_spec};
opendir(my $dh, $logdir) or die "Can't opendir $logdir: $!";
my @logfiles = grep { $_ =~ qr{$logfile_pattern} && -f $_ } map { File::Spec->catfile($logdir, $_) } readdir($dh);
closedir $dh;
$maxage =~ /(\d+)\s*?(year|month|week|day|hour|min(ute)?|sec(ond)?)s?/gmx;
my ($num, $unit) = ($1,$2);
usage() unless ($num && $unit);
my $maxage_seconds = $unit =~ /year/ ? ($num * 365 * 24 * 60 * 60)
: $unit =~ /month/ ? ($num * 30 * 24 * 60 * 60)
: $unit =~ /week/ ? ($num * 7 * 24 * 60 * 60)
: $unit =~ /day/ ? ($num * 24 * 60 * 60)
: $unit =~ /hour/ ? ($num * 60 * 60)
: $unit =~ /min(ute)?/ ? ($num * 60)
: $unit =~ /sec(ond)?/ ? ($num)
: ($num * 24 * 60 * 60);
my $oldest_timestamp = (scalar time) - $maxage_seconds;
warn Dumper(\@logfiles);
for my $file (@logfiles) {
next if ! -f $file;
my $timestamp = stat($file)->mtime;
# Check if file is older than max age and that it's not the file we are currently rotating to
if ( ( $timestamp < $oldest_timestamp) && ($file ne $logfile) ) {
debug("Deleting: '$file'\n");
unlink $file unless $NO_ACT;
} else {
debug("Skipping: '$file'\n");
}
}
sub usage {
print <<"USAGE_END";
Usage: $0 maxage([year|month|week|days|hours|mins|secs]s?):logfile-spec current_logfile
This command deletes files older than a certain max age matching a certain template.
The logfile-spec is in strftime format like cronolog itself.
It will not purge the passed current_logfile.
maxage defaults to seconds if no unit is given.
USAGE_END
;
exit 0;
}
sub debug {
print @_ if $DEBUG;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment