2011-01-06 17:28:35 +00:00
|
|
|
package Logger;
|
|
|
|
|
|
|
|
use strict;
|
|
|
|
use Thread::Queue;
|
|
|
|
use XML::Writer;
|
2016-05-26 13:14:07 +01:00
|
|
|
use Encode qw(decode encode);
|
2019-01-09 02:27:20 +00:00
|
|
|
use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
|
2011-01-06 17:28:35 +00:00
|
|
|
|
|
|
|
sub new {
|
|
|
|
my ($class) = @_;
|
|
|
|
|
|
|
|
my $logFile = defined $ENV{LOGFILE} ? "$ENV{LOGFILE}" : "/dev/null";
|
|
|
|
my $log = new XML::Writer(OUTPUT => new IO::File(">$logFile"));
|
|
|
|
|
|
|
|
my $self = {
|
|
|
|
log => $log,
|
|
|
|
logQueue => Thread::Queue->new()
|
|
|
|
};
|
|
|
|
|
|
|
|
$self->{log}->startTag("logfile");
|
|
|
|
|
|
|
|
bless $self, $class;
|
|
|
|
return $self;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub close {
|
|
|
|
my ($self) = @_;
|
|
|
|
$self->{log}->endTag("logfile");
|
|
|
|
$self->{log}->end;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub drainLogQueue {
|
|
|
|
my ($self) = @_;
|
|
|
|
while (defined (my $item = $self->{logQueue}->dequeue_nb())) {
|
|
|
|
$self->{log}->dataElement("line", sanitise($item->{msg}), 'machine' => $item->{machine}, 'type' => 'serial');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sub maybePrefix {
|
|
|
|
my ($msg, $attrs) = @_;
|
|
|
|
$msg = $attrs->{machine} . ": " . $msg if defined $attrs->{machine};
|
|
|
|
return $msg;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub nest {
|
|
|
|
my ($self, $msg, $coderef, $attrs) = @_;
|
|
|
|
print STDERR maybePrefix("$msg\n", $attrs);
|
|
|
|
$self->{log}->startTag("nest");
|
|
|
|
$self->{log}->dataElement("head", $msg, %{$attrs});
|
2019-01-09 02:27:20 +00:00
|
|
|
my $now = clock_gettime(CLOCK_MONOTONIC);
|
2011-01-06 17:28:35 +00:00
|
|
|
$self->drainLogQueue();
|
2011-01-09 18:46:02 +00:00
|
|
|
eval { &$coderef };
|
|
|
|
my $res = $@;
|
2011-01-06 17:28:35 +00:00
|
|
|
$self->drainLogQueue();
|
2019-01-09 02:27:20 +00:00
|
|
|
$self->log(sprintf("(%.2f seconds)", clock_gettime(CLOCK_MONOTONIC) - $now));
|
2011-01-06 17:28:35 +00:00
|
|
|
$self->{log}->endTag("nest");
|
2011-01-09 18:46:02 +00:00
|
|
|
die $@ if $@;
|
2011-01-06 17:28:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
sub sanitise {
|
|
|
|
my ($s) = @_;
|
|
|
|
$s =~ s/[[:cntrl:]\xff]//g;
|
2016-05-26 13:14:07 +01:00
|
|
|
$s = decode('UTF-8', $s, Encode::FB_DEFAULT);
|
|
|
|
return encode('UTF-8', $s, Encode::FB_CROAK);
|
2011-01-06 17:28:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
sub log {
|
|
|
|
my ($self, $msg, $attrs) = @_;
|
|
|
|
chomp $msg;
|
|
|
|
print STDERR maybePrefix("$msg\n", $attrs);
|
|
|
|
$self->drainLogQueue();
|
|
|
|
$self->{log}->dataElement("line", $msg, %{$attrs});
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|