2017-03-05 22:33:31 +01:00
|
|
|
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
|
2010-03-17 07:36:54 +01:00
|
|
|
package PBot::Logger;
|
|
|
|
|
|
|
|
use warnings;
|
|
|
|
use strict;
|
|
|
|
|
2019-07-11 03:40:53 +02:00
|
|
|
use feature 'unicode_strings';
|
|
|
|
|
2019-12-29 19:44:05 +01:00
|
|
|
use File::Basename;
|
2010-03-17 07:36:54 +01:00
|
|
|
use Carp ();
|
|
|
|
|
|
|
|
sub new {
|
2019-05-28 18:19:42 +02:00
|
|
|
if (ref($_[1]) eq 'HASH') {
|
2010-03-17 07:36:54 +01:00
|
|
|
Carp::croak("Options to Logger should be key/value pairs, not hash reference");
|
|
|
|
}
|
|
|
|
|
|
|
|
my ($class, %conf) = @_;
|
|
|
|
|
2019-12-29 19:44:05 +01:00
|
|
|
my $logfile = delete $conf{filename};
|
2010-03-17 07:36:54 +01:00
|
|
|
|
2019-12-29 19:44:05 +01:00
|
|
|
if (defined $logfile) {
|
|
|
|
my $path = dirname $logfile;
|
|
|
|
if (not -d $path) {
|
|
|
|
print "Creating new logfile path: $path\n";
|
|
|
|
mkdir $path or Carp::croak "Couldn't create logfile path: $!\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
open LOGFILE, ">>$logfile" or Carp::croak "Couldn't open logfile $logfile: $!\n";
|
|
|
|
LOGFILE->autoflush(1);
|
2010-03-17 07:36:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
my $self = {
|
2019-12-29 19:44:05 +01:00
|
|
|
logfile => $logfile,
|
2010-03-17 07:36:54 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
bless $self, $class;
|
|
|
|
return $self;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub log {
|
|
|
|
my ($self, $text) = @_;
|
|
|
|
my $time = localtime;
|
|
|
|
|
2017-09-05 09:18:35 +02:00
|
|
|
$text =~ s/(\P{PosixGraph})/my $ch = $1; if ($ch =~ m{[\s]}) { $ch } else { sprintf "\\x%02X", ord $ch }/ge;
|
2017-08-31 12:30:22 +02:00
|
|
|
|
2019-12-29 19:44:05 +01:00
|
|
|
if (defined $self->{logfile}) {
|
|
|
|
print LOGFILE "$time :: $text";
|
2019-06-26 18:34:19 +02:00
|
|
|
}
|
2010-03-17 07:36:54 +01:00
|
|
|
|
|
|
|
print "$time :: $text";
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|