2023-03-17 18:29:38 +03:00
|
|
|
package Log::Mini::Logger::Base;
|
2019-02-21 22:30:49 +03:00
|
|
|
|
|
|
|
use strict;
|
|
|
|
use warnings;
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
use Carp qw(croak);
|
2019-02-21 22:30:49 +03:00
|
|
|
use List::Util qw(first);
|
|
|
|
use Time::Moment;
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
|
2019-02-21 22:30:49 +03:00
|
|
|
my $LEVELS = {
|
|
|
|
error => 1,
|
|
|
|
warn => 2,
|
|
|
|
info => 3,
|
|
|
|
debug => 4,
|
2023-03-17 21:53:33 +03:00
|
|
|
trace => 5,
|
2019-02-21 22:30:49 +03:00
|
|
|
};
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
sub new
|
|
|
|
{
|
2019-02-21 22:30:49 +03:00
|
|
|
my $class = shift;
|
|
|
|
my (%params) = @_;
|
|
|
|
|
|
|
|
my $self = {};
|
|
|
|
bless $self, $class;
|
|
|
|
|
|
|
|
$self->{'level'} = $params{'level'} || 'error';
|
|
|
|
|
|
|
|
return $self;
|
|
|
|
}
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
sub set_level
|
|
|
|
{
|
2019-02-21 22:30:49 +03:00
|
|
|
my $self = shift;
|
|
|
|
my ($new_level) = @_;
|
|
|
|
|
|
|
|
croak('Unknown log level')
|
2023-03-17 18:29:38 +03:00
|
|
|
unless $LEVELS->{$new_level};
|
2019-02-21 22:30:49 +03:00
|
|
|
|
|
|
|
$self->{'level'} = $new_level;
|
|
|
|
|
2023-03-17 21:53:33 +03:00
|
|
|
return 1;
|
2019-02-21 22:30:49 +03:00
|
|
|
}
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
sub level
|
|
|
|
{
|
2019-02-21 22:30:49 +03:00
|
|
|
my $self = shift;
|
|
|
|
|
|
|
|
return $self->{level} || 'error';
|
|
|
|
}
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
sub log { return shift->_log(shift, @_) }
|
|
|
|
sub info { return shift->_log('info', @_) }
|
|
|
|
sub error { return shift->_log('error', @_) }
|
|
|
|
sub warn { return shift->_log('warn', @_) }
|
|
|
|
sub debug { return shift->_log('debug', @_) }
|
|
|
|
sub trace { return shift->_log('trace', @_) }
|
|
|
|
|
|
|
|
sub _log
|
|
|
|
{
|
|
|
|
my $self = shift;
|
|
|
|
my $level = shift;
|
2019-03-19 14:57:41 +03:00
|
|
|
my $message = shift;
|
2019-02-21 22:30:49 +03:00
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
return if $LEVELS->{$level} > $LEVELS->{$self->{'level'}};
|
2019-02-21 22:30:49 +03:00
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
my $time = $self->_getCurrentTime();
|
2019-02-21 22:30:49 +03:00
|
|
|
|
|
|
|
my $text = sprintf("%s [%s] %s\n", $time, $level, $message);
|
2019-03-19 14:57:41 +03:00
|
|
|
$text = sprintf($text, @_) if (@_);
|
2019-02-21 22:30:49 +03:00
|
|
|
|
|
|
|
$self->_print($text);
|
|
|
|
|
2023-03-17 21:53:33 +03:00
|
|
|
return 1;
|
2019-02-21 22:30:49 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
sub _print { croak 'Not implemented!' }
|
|
|
|
|
2023-03-17 18:29:38 +03:00
|
|
|
sub _getCurrentTime
|
|
|
|
{
|
|
|
|
return Time::Moment->now->strftime('%Y-%m-%d %T%3f');
|
|
|
|
}
|
|
|
|
|
2019-02-21 22:30:49 +03:00
|
|
|
1;
|