From: Will Budic Date: Fri, 6 Mar 2026 02:10:41 +0000 (+1100) Subject: Intr. flock of log thread safety. X-Git-Url: https://lifelog.hopto.org/gitweb/?a=commitdiff_plain;h=98824f44fa14e792d01b47eb46280e190918bc09;p=PerlCNF.git Intr. flock of log thread safety. --- diff --git a/system/modules/CNF.pm b/system/modules/CNF.pm index 63166f9..ac07918 100644 --- a/system/modules/CNF.pm +++ b/system/modules/CNF.pm @@ -9,6 +9,7 @@ use IO::Compress::Xz qw($XzError); use IO::Uncompress::UnXz qw($UnXzError); use File::ReadBackwards; use File::Copy; +use Fcntl qw(:flock); # Do not remove the following no critic, no security or object issues possible. # We can use perls default behavior on return. @@ -56,6 +57,7 @@ sub log { my $self = shift; my $message = shift; my $type = shift; $type = "" if !$type; + my $force_to_console = shift; my $isWarning = $type eq 'WARNG'; my $attach = join @_; $message .= $attach if $attach; my %log = $self -> property('%LOG'); @@ -68,7 +70,7 @@ sub log { $message =~ s/(\s+line\s)(\d+)\.*\s+/:$2\n/gm; print $time . " " .$message; } - elsif(%log && $log{console}){ + elsif(%log && ($force_to_console || $log{console})){ print $time . " " .$message ."\n" } if(%log && _isTrue($log{enabled}) && $message){ @@ -84,7 +86,9 @@ sub log { } if($LOG_FILE){ # now available do it open (my $fh, ">>", $LOG_FILE) or die $! . '->'. $LOG_FILE; + flock( $fh, LOCK_EX ); print $fh $time . " - " . $message ."\n"; + flock( $fh, LOCK_UN ); close $fh; if($LOG_TAIL_COUNT>0){ #2025-11-10 Mayor rewrite since v.3.3.6 Previous version was buffering and sorting unnecessary, slowing performance. @@ -100,6 +104,7 @@ sub log { my $tmpFile = ensureDir("/tmp/".$log); my $fh = File::ReadBackwards->new($LOG_FILE) or die $! . '->'. $LOG_FILE; my $cut = $LOG_CURRENT_LINE_CNT - $LOG_TAIL_COUNT; + open (my $fhTemp, ">", $tmpFile) or die $! . '->'. $tmpFile; for (1..$cut){ print $fhTemp $fh->readline() @@ -108,10 +113,12 @@ sub log { open (my $fhLog, ">", $LOG_FILE) or die $!; $fh = File::ReadBackwards->new($tmpFile) or die $! . '->'. $tmpFile; + flock( $fhLog, LOCK_EX ); for (1..$cut){ my $line = $fh->readline(); print $fhLog $line; } + flock( $fhLog, LOCK_UN ); close $fhLog; $fh->close(); $LOG_CURRENT_LINE_CNT = $cut; unlink $tmpFile