1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
|
#========================================================================
#
# Badger::Log
#
# DESCRIPTION
# A simple base class logging module.
#
# AUTHOR
# Andy Wardley <abw@wardley.org>
#
#========================================================================
package Badger::Log;
use Badger::Class
version => 0.01,
base => 'Badger::Prototype',
import => 'class',
utils => 'blessed Now',
config => 'system|class:SYSTEM format|class:FORMAT strftime|class:STRFTIME',
constants => 'ARRAY CODE',
constant => {
MSG => '_msg', # suffix for message methods, e.g. warn_msg()
LOG => 'log', # method a delegate must implement
},
vars => {
SYSTEM => 'Badger',
FORMAT => '[<time>] [<system>] [<level>] <message>',
STRFTIME => '%a %b %d %T %Y',
LEVELS => {
debug => 0,
info => 0,
warn => 1,
error => 1,
fatal => 1,
}
},
messages => {
bad_level => 'Invalid logging level: %s',
};
class->methods(
# Our init method is called init_log() so that we can use Badger::Log as
# a mixin or base class without worrying about the init() method clashing
# with init() methods from other base classes or mixins. We create an
# alias from init() to init_log() so that it also Just Works[tm] as a
# stand-alone object
init => \&init_log,
# Now we define two methods for each logging level. The first expects
# a pre-formatted output message (e.g. debug(), info(), warn(), etc)
# the second additionally wraps around the message() method inherited
# from Badger::Base (eg. debug_msg(), info_msg(), warn_msg(), etc)
map {
my $level = $_; # lexical variable for closure
$level => sub {
my $self = shift;
return $self->{ $level } unless @_;
$self->log($level, @_)
if $self->{ $level };
},
($level.MSG) => sub {
my $self = shift;
return $self->{ $level } unless @_;
$self->log($level, $self->message(@_))
if $self->{ $level };
}
}
keys %$LEVELS
);
sub init_log {
my ($self, $config) = @_;
my $class = $self->class;
my $levels = $class->hash_vars( LEVELS => $config->{ levels } );
# populate $self for each level in $LEVEL using the
# value in $config, or the default in $LEVEL
while (my ($level, $default) = each %$levels) {
$self->{ $level } =
defined $config->{ $level }
? $config->{ $level }
: $levels->{ $level };
}
# call the auto-generated configure() method to update $self from $config
$self->configure($config);
return $self;
}
sub log {
my $self = shift;
my $level = shift;
my $action = $self->{ $level };
my $message = join('', @_);
my $method;
return $self->_fatal_msg( bad_level => $level )
unless defined $action;
# depending on what the $action is set to, we add the message to
# an array, call a code reference, delegate to another log object,
# print or ignore the mesage
if (ref $action eq ARRAY) {
push(@$action, $message);
}
elsif (ref $action eq CODE) {
&$action($level, $message);
}
elsif (blessed $action && ($method = $action->can(LOG))) {
$method->($action, $level, $message);
}
elsif ($action) {
warn $self->format($level, $message), "\n";
}
}
sub format {
my $self = shift;
my $args = {
time => Now->format($self->{ strftime }),
system => $self->{ system },
level => shift,
message => shift,
};
my $format = $self->{ format };
$format =~
s/<(\w+)>/
defined $args->{ $1 }
? $args->{ $1 }
: "<$1>"
/eg;
return $format;
}
sub level {
my $self = shift;
my $level = shift;
return $self->_fatal_msg( bad_level => $level )
unless exists $LEVELS->{ $level };
return @_ ? ($self->{ $level } = shift) : $self->{ $level };
}
sub enable {
my $self = shift;
$self->level($_ => 1) for @_;
}
sub disable {
my $self = shift;
$self->level($_ => 0) for @_;
}
sub _error_msg {
my $self = shift;
$self->Badger::Base::error(
$self->Badger::Base::message(@_)
);
}
sub _fatal_msg {
my $self = shift;
$self->Badger::Base::fatal(
$self->Badger::Base::message(@_)
);
}
1;
__END__
=head1 NAME
Badger::Log - log for errors, warnings and other messages
=head1 SYNOPSIS
use Badger::Log;
my $log = Badger::Log->new({
debug => 0, # ignore debug messages
info => 1, # print info messages
warn => \@warn, # add warnings to list
error => $log2, # delegate errors to $log2
fatal => sub { # custom fatal error handler
my $message = shift;
print "FATAL ERROR: $message\n";
},
});
$log->debug('a debug message');
$log->info('an info message');
$log->warn('a warning message');
$log->error('an error message');
$log->fatal('a fatal error message');
=head1 DESCRIPTION
This module defines a simple base class module for logging messages
generated by an application. It is intentionally very simple in design,
providing the bare minimum in functionality with the possibility for
extension by subclassing.
It offers little, if anything, over the many other fine logging modules
available from CPAN. It exists to provide a basic logging facility
that integrates cleanly with, and can be bundled up with the other Badger
modules so that you've got something that works "out of the box".
There are five message categories:
=over
=item debug
A debugging message.
=item info
A message providing some general information.
=item warn
A warning message.
=item error
An error message.
=item fatal
A fatal error message.
=back
=head1 CONFIGURATION OPTIONS
=head2 debug
Flag to indicate if debugging messages should be generated and output.
The default value is C<0>. It can be set to C<1> to enable debugging
messages or to one of the other reference values described in the
documentation for the L<new()> method.
=head2 info
Flag to indicate if information messages should be generated and output.
The default value is C<0>. It can be set to C<1> to enable information
messages or to one of the other reference values described in the
documentation for the L<new()> method.
=head2 warn
Flag to indicate if warning messages should be generated and output.
The default value is C<1>. It can be set to C<0> to disable warning
messages or to one of the other reference values described in the
documentation for the L<new()> method.
=head2 error
Flag to indicate if error messages should be generated and output.
The default value is C<1>. It can be set to C<0> to disable error
messages or to one of the other reference values described in the
documentation for the L<new()> method.
=head2 fatal
Flag to indicate if fatal messages should be generated and output. The default
value is C<1>. It can be set to C<0> to disable fatal error messages (at your
own peril) or to one of the other reference values described in the
documentation for the L<new()> method.
=head2 format
This option can be used to define a different log message format.
my $log = Badger::Log->new(
format => '[<level>] [<time>] <message>',
);
The default message format is:
[<time>] [<system>] [<level>] <message>
The C<E<lt>XXXE<gt>> snippets are replaced with their equivalent values:
time The current local time
system A system identifier, defaults to 'Badger'
level The message level: debug, info, warn, error or fatal
message The log message itself
The format can also be set using a C<$FORMAT> package variable in a subclass
of C<Badger::Log>.
package Your::Log::Module;
use base 'Badger::Log';
our $FORMAT = '[<level>] [<time>] <message>';
1;
=head2 system
A system identifier which is inserted into each message via the
C<E<lt>systemE<gt>> snippet. See L<format> for further information.
The default value is C<Badger>.
my $log = Badger::Log->new(
system => 'MyApp',
);
The system identifier can also be set using a C<$SYSTEM> package variable in a
subclass of C<Badger::Log>.
package Your::Log::Module;
use base 'Badger::Log';
our $SYSTEM = 'MyApp';
1;
=head2 strftime
This option can be used to set the format for the timestamp added to messages
via the via the C<E<lt>time<gt>> snippet.
my $log = Badger::Log->new(
strftime => '%a %b %d %Y',
);
The format string is passed to the L<format()|Badger::Timestamp/format()>
method of L<Badger::Timestamp>.
=head1 METHODS
=head2 new(\%options)
Constructor method which creates a new C<Badger::Log> object. It
accepts a list of named parameters or reference to hash of
configuration options that define how each message type should be
handled.
my $log = Badger::Log->new({
debug => 0, # ignore debug messages
info => 1, # print info messages
warn => \@warn, # add warnings to list
error => $log2, # delegate errors to $log2
fatal => sub { # custom fatal error handler
my $message = shift;
print "FATAL ERROR: $message\n";
},
});
Each message type can be set to C<0> to ignore messages or C<1> to
have them printed to C<STDERR>. They can also be set to reference a list
(the message is appended to the list), a subroutine (which is called,
passing the message as an argument), or any object which implements a
L<log()> method (to which the message is delegated).
=head2 debug($message)
Generate a debugging message.
$log->debug('The cat sat on the mat');
=head2 info($message)
Generate an information message.
$log->info('The pod doors are closed');
=head2 warn($message)
Generate a warning message.
$log->warn('The pod doors are opening');
=head2 error($message)
Generate an error message.
$log->error("I'm sorry Dave, I can't do that');
=head2 fatal($message)
Generate a fatal error message.
$log->fatal('HAL is dead, aborting mission');
=head2 debug_msg($format,@args)
This method uses the L<message()|Badger::Base/message()> method inherited
from L<Badger::Base> to generate a debugging message from the arguments
provided. To use this facility you first need to create your own logging
subclass which defines the message formats that you want to use.
package Your::Log;
use base 'Badger::Log';
our $MESSAGES = {
denied => "Denied attempt by %s to %s",
};
1;
You can now use your logging module like so:
use Your::Log;
my $log = Your::Log->new;
$log->debug_msg( denied => 'Arthur', 'make tea' );
The log message generated will look something like this:
# TODO
=head2 info_msg($format,@args)
This method uses the L<message()|Badger::Base/message()> method inherited
from L<Badger::Base> to generate an info message from the arguments
provided. See L<debug_msg()> for an example of using message formats.
=head2 warn_msg($format,@args)
This method uses the L<message()|Badger::Base/message()> method inherited
from L<Badger::Base> to generate a warning message from the arguments
provided. See L<debug_msg()> for an example of using message formats.
=head2 error_msg($format,@args)
This method uses the L<message()|Badger::Base/message()> method inherited
from L<Badger::Base> to generate an error message from the arguments
provided. See L<debug_msg()> for an example of using message formats.
=head2 fatal_msg($format,@args)
This method uses the L<message()|Badger::Base/message()> method inherited
from L<Badger::Base> to generate a fatal error message from the arguments
provided. See L<debug_msg()> for an example of using message formats.
=head2 log($level, $message)
This is the general-purpose logging method that the above methods call.
$log->log( info => 'star child is here' );
=head2 level($level, $action)
This method is used to get or set the action for a particular level.
When called with a single argument, it returns the current action
for that level.
my $debug = $log->level('debug');
When called with two arguments it sets the action for the log level
to the second argument.
$log->level( debug => 0 ); # disable
$log->level( info => 1 ); # enable
$log->level( warn => $list ); # push to list
$log->level( error => $code ); # call code
$log->level( fatal => $log2 ); # delegate to another log
=head2 enable($level)
This method can be used to enable one or more logging levels.
$log->enable('debug', 'info', 'warn');
=head2 disable($level)
This method can be used to disable one or more logging levels.
$log->disable('error', 'fatal');
=head1 INTERNAL METHODS
=head2 _error_msg($format,@args)
The L<error_msg()> method redefines the L<error_msg()|Badger::Base/error_msg()>
method inherited from L<Badger::Base> (which can be considered both a bug and
a feature). The internal C<_error_msg()> method effectively bypasses the
new method and performs the same functionality as the base class method, in
throwing an error as an exception.
=head2 _fatal_msg($format,@args)
As per L<_error_msg()>, this method provides access to the functionality
of the L<fatal_msg()|Badger::Base/fatal_msg()> method in L<Badger::Base>.
=head1 AUTHOR
Andy Wardley L<http://wardley.org/>
=head1 COPYRIGHT
Copyright (C) 2005-2022 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 SEE ALSO
L<Badger::Log::File>
=cut
# Local Variables:
# mode: perl
# perl-indent-level: 4
# indent-tabs-mode: nil
# End:
#
# vim: expandtab shiftwidth=4:
|