#!/usr/bin/perl # a40405.pl 2007-9-29 by akebia # Simple logrotate # http://nyan.co.uk/akebia/item/80 $log_file = ['*.log']; $log_rotatetime = 604800; $log_rotate = 52; $log_ifempty = 0; $log_compdly = 2; $log_compcmd = ['`gzip -n "$f.$z"`']; $log_compext = 'gz'; $log_prerotate = ['']; $log_postrotate = ['']; my $t, $r, $m, $p, $u, $x, $z, $l, @f, $f = ''; my %a = (); my $wi, $wj, $wp, $wu; foreach(@ARGV){ if(substr($_, 0, 1) eq '-'){$f = $_; $a{$f} = []; next;} if($f ne ''){push(@{$a{$f}}, $_);} else {push(@{$a{'-f'}}, $_);} } if($a{'-f'}){$log_file = $a{'-f'};} if($a{'-t'}){$log_rotatetime = $a{'-t'}[0];} $t = $log_rotatetime; if($a{'-r'}){$log_rotate = $a{'-r'}[0];} $r = $log_rotate; if($a{'-i'}){$log_ifempty = 1; } $i = $log_ifempty; if($a{'-z'}){$log_compdly = $a{'-z'}[0];} $z = $log_compdly; if($a{'-m'}){$log_compcmd = $a{'-m'};} $m = join(" ", @$log_compcmd); if($a{'-x'}){$log_compext = $a{'-x'}[0];} $x = $log_compext; if($a{'-p'}){$log_prerotate = $a{'-p'};} $p = join(" ", @$log_prerotate); if($a{'-u'}){$log_postrotate = $a{'-u'};} $u = join(" ", @$log_postrotate); @f = <@$log_file>; $wp = 0; $wu = 0; foreach $f (@f){ unless($i){if(-z $f){next;}} $l = (stat("$f.1"))[9]; if($l eq ''){$l = (stat("$f.1.$x"))[9];} if($l ne ''){if(time - $l < $t){next;}}else{$l = time - $t;} $wu = 1; $wj = 0; for($wi = $r; $wi > 1; $wi--){ if($wj < 2){ if(-e "$f.$wi" || -e "$f.$wi.$x"){$wj = 1;} else{if($wj > 0){$wj = 2; $wi++;}} }else{ rename("$f.".($wi - 1), "$f.$wi"); rename("$f.".($wi - 1).".$x", "$f.$wi.$x"); } } if($wj < 2){ unless($wp){$wp = 1; eval($p);} unlink("$f.$r"); unlink("$f.$r.$x"); for($wi = $r; $wi > 1; $wi--){ rename("$f.".($wi - 1), "$f.$wi"); rename("$f.".($wi - 1).".$x", "$f.$wi.$x"); } } rename($f, "$f.1"); $l += int((time - $l) / $t) * $t; utime(undef, $l, "$f.1"); utime(undef, $l, "$f.1.$x"); } if($wu){eval($u); if($z){foreach $f (@f){if(-e "$f.$z"){eval($m);}}}}