update DWeather::Debug, Logger, Serial
[dweather.git] / DWeather / lib / DWeather / Logger.pm
index b8233bfb0c9c13e928aafe7ddea2da662a93998c..98fba0547a872bfb828c91fcee83652e69951828 100644 (file)
@@ -25,6 +25,7 @@ use File::Path;
 
 @ISA = qw(Exporter);
 @EXPORT = qw(Log LogDbg);
+$VERSION = 1.20;
 
 use strict;
 
@@ -32,11 +33,14 @@ use vars qw($log $path);
 $log = undef;
 $path = './logs';
 
+my %open;
+
+init();
+
 # make the Log() export use this default file
 sub init
 {
-       my $default_dir = shift || 'sys_log';
-       $log = __PACKAGE__->new($default_dir) unless $log;
+       $log = __PACKAGE__->new("sys_log");
 }
 
 # create a log object that contains all the useful info needed
@@ -54,7 +58,16 @@ sub new
        mkpath($dir, 0, 0777) unless -d $dir;
        die "cannot create or access $dir $!" unless -d $dir;
        
-       return bless $ref, $pkg;
+       my $self = bless $ref, $pkg;
+       $open{$self} = $self;
+       return $self;
+}
+
+sub mode
+{
+       my $self = shift;
+       $self->{mode} = shift if @_;
+       return $self->{mode};
 }
 
 # open the appropriate data file
@@ -75,12 +88,12 @@ sub open
        $self->{fn} = sprintf "$self->{prefix}/$year/%02d%02d", $month, $day;
        $self->{fn} .= ".$self->{suffix}" if $self->{suffix};
        
-       $self->{mode} = $mode || 'r';
+       $self->{mode} = $mode || 'a+';
        
        my $fh = new IO::File $self->{fn}, $mode, 0666;
        return unless $fh;
        
-       $fh->autoflush(1) if $mode ne 'r'; # make it autoflushing if writable
+       $fh->autoflush(0) if $mode ne 'r'; # disable autoflushing if writable
        $self->{fh} = $fh;
 
        $self->{year} = $year;
@@ -111,10 +124,8 @@ sub opennext
 sub write
 {
        my ($self, $dayno, $line) = @_;
-       if (!$self->{fh} || 
-               $self->{mode} ne ">>" || 
-               $dayno != $self->{dayno}) {
-               $self->open($dayno, ">>") or confess "can't open $self->{fn} $!";
+       if (!$self->{fh} || $self->{mode} ne "r" || $dayno != $self->{dayno}) {
+               $self->open($dayno, "a+") or confess "can't open $self->{fn} $!";
        }
 
        return $self->{fh}->print("$line\n");
@@ -155,10 +166,27 @@ sub close
 sub DESTROY
 {
        my $self = shift;
+
+       delete $open{$self};
        undef $self->{fh};                      # close the filehandle
        delete $self->{fh} if $self->{fh};
 }
 
+sub flush
+{
+       $_[0]->{fh}->flush if $_[0]->{fh};
+}
+
+sub flushall
+{
+       foreach my $v (values %open) {
+               $v->flush;
+       }
+}
+
+sub flush_all { goto &flushall }
+
+
 sub Log
 {
        my $l = ref $_[0] ? shift : $log;
@@ -171,9 +199,7 @@ sub Log
 sub LogDbg
 {
     Log(@_);
-    DWeather::Debug::dbg(@_) if DWeather::Debug::isdbg('chan');
+    Debug::dbg(@_) if Debug::isdbg('chan');
 }
 
-init();
-
 1;