HTTP::Daemon::Threaded::Logger
package HTTP::Daemon::Threaded::Logger;
use Thread::Apartment::Server;
use Time::Local;
use base qw(Thread::Apartment::Server);
use strict;
use warnings;
our $VERSION = '0.91';
sub new {
my ($class, %args) = @_;
#
# make sure we can open the logfile
#
my $self = { %args };
bless $self, $class;
$self->set_client(delete $self->{AptTAC})
if $self->{AptTAC};
my $logfd;
$@ = "Can't open logfile: $!",
return undef
unless open($logfd, ">>$self->{Path}");
my $old_fh = select($logfd);
$| = 1;
select($old_fh);
$self->{_fd} = $logfd;
#
# get current logfile size and last modify time
# if bigger than maxsize, or older than lifetime, truncate it
#
my @logstats = stat $logfd;
$self->{_logsize} = $logstats[7];
$self->{_logtime} = $logstats[9];
$self->truncate()
if (($args{MaxSize} && ($self->{_logsize} > $args{MaxSize})) ||
($args{Lifetime} && ((time() - $self->{_logtime}) > $args{Lifetime})));
$self->log("**************************************");
$self->log('Logger: HTTP::Daemon::Threaded started.');
return $self;
}
sub get_simplex_methods {
return {
'log' => 1,
'close' => 1,
'truncate' => 1,
'handleExpiration' => 1,
'updateLifetime' => 1,
'updateMaxSize' => 1
};
}
sub log {
my ($self, $msg) = @_;
my $fd = $self->{_fd};
return undef
unless $fd;
$msg = scalar localtime() . ": $msg\n";
$self->{_logsize} += length($msg);
print $fd $msg;
return $self;
}
sub close {
my $self = shift;
my $fd = delete $self->{_fd};
close($fd)
if $fd;
return $self;
}
sub truncate {
my ($self, $newpath) = @_;
#
# close existing file
# rename it with timestamp
# open new file
# reset size/time
#
$newpath = $self->{Path}
unless $newpath;
my $fd = delete $self->{_fd};
CORE::close($fd)
if $fd;
my @ts = split(/\s+/, scalar localtime());
$ts[3]=~tr/:/_/;
my $sfx = join('', '.', $ts[4], $ts[1], $ts[2], '_', $ts[3]);
print STDERR "HTTP::Daemon::Threaded::Logger::truncate: Can't rename logfile: $!" and
return undef
unless rename $self->{Path}, $self->{Path} . $sfx;
$self->{_logsize} = 0;
$self->{_logtime} = time();
print STDERR "HTTP::Daemon::Threaded::Logger::truncate: Can't open logfile: $!" and
return undef
unless open($fd, ">$newpath");
my $old_fh = select($fd);
$| = 1;
select($old_fh);
$self->{_fd} = $fd;
$self->log("**************************************");
$self->log('Logger: Logfile truncated.');
}
sub updateLifetime {
$_[0]->{Lifetime} = $_[1];
}
sub updateMaxSize {
$_[0]->{MaxSize} = $_[1];
}
sub updatePath {
my ($self, $newpath) = @_;
$self->truncate($newpath);
$self->{Path} = $newpath;
}
1;