[Melbourne-pm] An intermittent problem with open for append

Craig Sanders cas at taz.net.au
Wed May 28 16:08:45 PDT 2008


On Wed, May 28, 2008 at 10:04:00PM +1000, Jacinta Richardson wrote:
> In this kind of instance, I'd recommend:
> 
> 	if(open OUT, ">>/home/foo/que/$ip") {
> 		print OUT "$ip:t:date=",scalar localtime,"\n";
> 	}
> 	else {
> 		push @error, "Can't save details";
> 	}

in this instance, i'd recommend something very similar, but more like this:

 	my $logdir='/home/foo/que';
 	my $outfile="$logdir/$ip";

 	if(open(OUT,'>>',$outfile)) {
 		print OUT "$ip:t:date=",scalar localtime,"\n";
 	}
 	else {
 		push @error, "Can't open $outfile for append: $!";
 	}

advantages:

1. 3-argument open() is better practice, especially if there's a chance
   that the filename is based on user input. always using the 3-arg form
   of open() is a good habit to get into.

2. "Can't save details" is a useless error message.  I've updated it
   to say specifically what the problem was - including the filename and
   "$!" aka $OS_ERROR, which is the actual error message returned by the
   operating system.

3. hard-coding directory names is bad.  it's always good to make
   things easy for yourself - or your successor - in case you/they
   need to move things around later.  put stuff like $logdir in
   a "configuration" or "constants" section at the top of the script
   to make them easy to find and change later.


more general comments:

at a guess, i'd say that "$ip" is probably the IP address of the remote
client and that the OP wants to have a separate log file per IP address.

it's hard to imagine why that would or could be a good idea.  IMO, it's
better to write to just one log file and include sufficient information
in the log entries that you can extract whatever you need from it
later with grep or some post-processing script.  

hundreds or thousands of little log files just makes for clutter, and
makes management of the log files (e.g. daily or weekly rotation) more
difficult.

also, on some filesystem, it seriously impacts performance because
having thousands of little files in one directory slows down all file
access in that directory.


craig

-- 
craig sanders <cas at taz.net.au>


More information about the Melbourne-pm mailing list