Why use a module? It's simple to implement with Perl's
file locking interface. See "perldoc -f flock".
use strict;
use warnings;
use Fcntl qw/:flock/;
open my $fh,'>>','file.log' or die $!; # open file
flock $fh,LOCK_EX or die $!; # lock file
print $fh "message\n" or die $!; # write file
close $fh or die $!; # close file
At least on unixish systems locking the file isn't necessary if you can
ensure that you always write a log entry with a single write(2) system
call. PerlIO seems to do this if you open a file in raw mode:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Handle;
open my $fh, ">:raw", "foo.out";
$fh->autoflush(1);
my $s = "a" x 100 . "\n";
print $fh $s;
$s = "a" x 10_000 . "\n";
print $fh $s;
$s = "a" x 1000;
print $fh $s, $s, $s, $s, "\n";
__END__
strace shows:
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 101) = 101
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 10001) = 10001
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 1000) = 1000
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 1000) = 1000
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 1000) = 1000
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 1000) = 1000
write(3, "\n", 1) = 1
The first and second writes correlate to the first and second print statement.
The next 5 writes correlate to the 5 arguments of the third print statement.
Remove ":raw" from th open call and the strace output looks like this:
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 101) = 101
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 4096) = 4096
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 4096) = 4096
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 1809) = 1809
write(3, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"..., 4001) = 4001
The first print statement is again turned into single write call. But the
second string (being longer than the buffer length) is split into three
write calls, and the 5 arguments of the third print statement (being
shorter than the buffer length) are gathered into a single write call.
hp