Category: | Utility Scripts |
Author/Contact Info | danikar@gmail.com |
Description: | A small script I wrote for work. My first script that is going to be used for anything real, so I am pretty nervous putting it into practice tomorrow. I figured I would throw it up here and see if anyone had any suggestions and so forth. The key thing is that so far it seems to work. Also, I know very little about log rotation, so hopefully I got the concept down heh. I used a few `command` to archive old logs, I am sure there is a perl module out there for it, but time was for the essence in here. Any suggestions to switch that stuff out with I am open to. Date time stamp isn't working correctly. =\ |
#/usr/bin/perl use strict; my $dir = "/var/log"; # Location of the Log file my $logfile = "log.txt"; # Name of the Log file my $maxsize = 2_000_000; # Max size before rotating my $maxlogs = 10; # Number of rotates before archive my $archivetotal = 5; # Number of logs to archive my ($s, $m, $h, $dayOfMonth, $month, # Create date from + local time $yearOffset, $dow, $doy, $dst) = localtime(); my $year = 1900 + $yearOffset; my $date = $year * 1000 + ($month + 1) * 100 + $dayOfMonth; # Forma +t Date my $tarme; # Store names of files to be archived ### Switch to directory where log file is located chdir $dir; ### Check Size of log if(-s $logfile > $maxsize) { ### Rotate old logs for(my $i = $maxlogs - 1;$i > 0;$i--) { if(-e "${logfile}.$i") { my $j = $i + 1; rename "${logfile}.$i", "${logfile}.$j"; } } rename "$logfile", "${logfile}.1"; `echo "" >> $logfile`; ### Archive logs if(-e "${logfile}.$maxlogs") { for(my $i = $maxlogs - ($archivetotal - 1), my $j = 1;$i <= $m +axlogs;$i++, $j++) { rename "${logfile}.$i", "${logfile}.${date}.$j"; $tarme .= "${logfile}.${date}.$j "; } my $i = 1; my $tarfile = "${logfile}.${date}.tar"; while ( (-e $tarfile) || (-e "${tarfile}.gz") ) { $tarfile = "${logfile}.${date}.tar.$i"; $i++; } `tar -czf $tarfile $tarme`; `rm $tarme`; `gzip $tarfile`; } } else { print "Log file too small to rotate.\n\n"; } |
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Log Rotation
by andreas1234567 (Vicar) on Nov 23, 2007 at 09:06 UTC | |
by Danikar (Novice) on Nov 23, 2007 at 10:27 UTC | |
Re: Log Rotation
by tirwhan (Abbot) on Nov 23, 2007 at 12:36 UTC | |
by Danikar (Novice) on Nov 23, 2007 at 17:09 UTC | |
by tcf03 (Deacon) on Nov 27, 2007 at 16:08 UTC |