Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with log file script!! 1

Status
Not open for further replies.

roman78

Technical User
Jun 28, 2004
7
MX
I'm writing a perl script that would help me to learn howto create a file log rotator that will simulate the real /var/log/messages. This script checks and creates these files: messages, messades1, messages2, messages3, messages4.
The first one represents the current log and the others are older versions. Each time the script runs it should check for the existance of messages.3 and, if it exists, move it to messages.4. Then is should check for messages.2 and move it to messages.3 and so on, until messages is moved to messages1,
This is the script:

#!/usr/bin/perl

open(LOG,">messages");

$logfile = $ARGV[0] ;
$to_num = $ARGV[5] ;
while($to_num > 1)
{
$from_num = $to_num - 1 ;
if(-f "$logfile.$from_num")
{
system("/bin/mv $logfile.$from_num $logfile.$to_num") ;
}
$to_num-- ;
}

if(-f $logfile)
system("/bin/cp $logfile $logfile.1") ;
system("/bin/cp /dev/null $logfile") ;
}

and finally it migth be run once a week by cron to help organize the log files.

my problem is that the script is not working.I am confused about how to create the 5 messages files at the same time(files that are created every time the script is running), and I know it has a few mistakes but as a perl newbie I can't get this script working. Does anybody help me?,
please
Many thanks...
 
The code below should do what you're looking for. The only other consideration would be how active the log is. Is it possible that, when you rename the messages file to messages.1, something would be trying to write to the log?

Code:
my $logpath = '/some/dir/';
my $logfile = $ARGV[0] ||= "messages";
my $max_files = $ARGV[5] ||= 5;

# Renames old files
foreach (reverse 1..($max_files - 1)) {
    my $from_num = $_ - 1;
    if (-e "$logpath$logfile.$from_num") {
        rename "$logpath$logfile.$from_num", "$logpath$logfile.$_";
    }
}

# Renames current log file
if (-e "$logpath$logfile") {
    rename "$logpath$logfile", "$logpath$logfile.1";
}

# Creates new log
open LOG, "> $logpath$logfile" or die "Cannot create log.\n$!\n";
close LOG;
 
if you're on *nix, you should be able to use symlinks to manage what file is what regardless of their physical names, assuming you know what they are (which makes the statement "regardless" redundant!!!)

Have't done it, but it strikes me that it is eminently doable ..

--Paul

It's important in life to always strike a happy medium, so if you see someone with a crystal ball, and a smile on their face ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top