NAME
Log::Contextual - Simple logging interface with a contextual log
SYNOPSIS
use Log::Contextual qw( :log :dlog set_logger with_logger );
use Log::Contextual::SimpleLogger;
use Log::Log4perl ':easy';
Log::Log4perl->easy_init($DEBUG);
my $logger = Log::Log4perl->get_logger;
set_logger $logger;
log_debug { 'program started' };
sub foo {
my $minilogger = Log::Contextual::SimpleLogger->new({
levels => [qw( trace debug )]
});
with_logger $minilogger => sub {
log_trace { 'foo entered' };
my ($foo, $bar) = Dlog_trace { "params for foo: $_" } @_;
# ...
log_trace { 'foo left' };
};
}
foo();
Beginning with version 1.008 Log::Dispatchouli also works out of the box with Log::Contextual
:
use Log::Contextual qw( :log :dlog set_logger );
use Log::Dispatchouli;
my $ld = Log::Dispatchouli->new({
ident => 'slrtbrfst',
to_stderr => 1,
debug => 1,
});
set_logger $ld;
log_debug { 'program started' };
DESCRIPTION
Major benefits:
Efficient
The logging functions take blocks, so if a log level is disabled, the block will not run:
# the following won't run if debug is off log_debug { "the new count in the database is " . $rs->count };
Similarly, the
D
prefixed methods onlyDumper
the input if the level is enabled.Handy
The logging functions return their arguments, so you can stick them in the middle of expressions:
for (log_debug { "downloading:\n" . join qq(\n), @_ } @urls) { ... }
Generic
Log::Contextual
is an interface for all major loggers. If you log throughLog::Contextual
you will be able to swap underlying loggers later.Powerful
Log::Contextual
chooses which logger to use based on user definedCodeRef
s. Normally you don't need to know this, but you can take advantage of it when you need to laterScalable
If you just want to add logging to your extremely basic application, start with Log::Contextual::SimpleLogger and then as your needs grow you can switch to Log::Dispatchouli or Log::Dispatch or Log::Log4perl or whatever else.
This module is a simple interface to extensible logging. It exists to abstract your logging interface so that logging is as painless as possible, while still allowing you to switch from one logger to another.
It is bundled with a really basic logger, Log::Contextual::SimpleLogger, but in general you should use a real logger instead of that. For something more serious but not overly complicated, try Log::Dispatchouli (see "SYNOPSIS" for example.)
A WORK IN PROGRESS
This module is certainly not complete, but we will not break the interface lightly, so I would say it's safe to use in production code. The main result from that at this point is that doing:
use Log::Contextual;
will die as we do not yet know what the defaults should be. If it turns out that nearly everyone uses the :log
tag and :dlog
is really rare, we'll probably make :log
the default. But only time and usage will tell.
IMPORT OPTIONS
See "SETTING DEFAULT IMPORT OPTIONS" for information on setting these project wide.
-logger
When you import this module you may use -logger
as a shortcut for set_logger, for example:
use Log::Contextual::SimpleLogger;
use Log::Contextual qw( :dlog ),
-logger => Log::Contextual::SimpleLogger->new({ levels => [qw( debug )] });
sometimes you might want to have the logger handy for other stuff, in which case you might try something like the following:
my $var_log;
BEGIN { $var_log = VarLogger->new }
use Log::Contextual qw( :dlog ), -logger => $var_log;
-levels
The -levels
import option allows you to define exactly which levels your logger supports. So the default, [qw(debug trace warn info error fatal)]
, works great for Log::Log4perl, but it doesn't support the levels for Log::Dispatch. But supporting those levels is as easy as doing
use Log::Contextual
-levels => [qw( debug info notice warning error critical alert emergency )];
-package_logger
The -package_logger
import option is similar to the -logger
import option except -package_logger
sets the the logger for the current package.
Unlike "-default_logger", -package_logger
cannot be overridden with "set_logger".
package My::Package;
use Log::Contextual::SimpleLogger;
use Log::Contextual qw( :log ),
-package_logger => Log::Contextual::WarnLogger->new({
env_prefix => 'MY_PACKAGE'
});
If you are interested in using this package for a module you are putting on CPAN we recommend Log::Contextual::WarnLogger for your package logger.
-default_logger
The -default_logger
import option is similar to the -logger
import option except -default_logger
sets the the default logger for the current package.
Basically it sets the logger to be used if set_logger
is never called; so
package My::Package;
use Log::Contextual::SimpleLogger;
use Log::Contextual qw( :log ),
-default_logger => Log::Contextual::WarnLogger->new({
env_prefix => 'MY_PACKAGE'
});
SETTING DEFAULT IMPORT OPTIONS
Eventually you will get tired of writing the following in every single one of your packages:
use Log::Log4perl;
use Log::Log4perl ':easy';
BEGIN { Log::Log4perl->easy_init($DEBUG) }
use Log::Contextual -logger => Log::Log4perl->get_logger;
You can set any of the import options for your whole project if you define your own Log::Contextual
subclass as follows:
package MyApp::Log::Contextual;
use base 'Log::Contextual';
use Log::Log4perl ':easy';
Log::Log4perl->easy_init($DEBUG)
sub arg_default_logger { $_[1] || Log::Log4perl->get_logger }
sub arg_levels { [qw(debug trace warn info error fatal custom_level)] }
# or maybe instead of default_logger
sub arg_package_logger { $_[1] }
# and almost definitely not this, which is only here for completeness
sub arg_logger { $_[1] }
Note the $_[1] ||
in arg_default_logger
. All of these methods are passed the values passed in from the arguments to the subclass, so you can either throw them away, honor them, die on usage, or whatever. To be clear, if you define your subclass, and someone uses it as follows:
use MyApp::Log::Contextual -default_logger => $foo,
-levels => [qw(bar baz biff)];
Your arg_default_logger
method will get $foo
and your arg_levels
will get [qw(bar baz biff)]
;
FUNCTIONS
set_logger
my $logger = WarnLogger->new;
set_logger $logger;
Arguments: "LOGGER CODEREF"
set_logger
will just set the current logger to whatever you pass it. It expects a CodeRef
, but if you pass it something else it will wrap it in a CodeRef
for you. set_logger
is really meant only to be called from a top-level script. To avoid foot-shooting the function will warn if you call it more than once.
with_logger
my $logger = WarnLogger->new;
with_logger $logger => sub {
if (1 == 0) {
log_fatal { 'Non Logical Universe Detected' };
} else {
log_info { 'All is good' };
}
};
Arguments: "LOGGER CODEREF", CodeRef $to_execute
with_logger
sets the logger for the scope of the CodeRef
$to_execute
. As with "set_logger", with_logger
will wrap $returning_logger
with a CodeRef
if needed.
log_$level
Import Tag: :log
Arguments: CodeRef $returning_message, @args
log_$level
functions all work the same except that a different method is called on the underlying $logger
object. The basic pattern is:
sub log_$level (&@) {
if ($logger->is_$level) {
$logger->$level(shift->(@_));
}
@_
}
Note that the function returns it's arguments. This can be used in a number of ways, but often it's convenient just for partial inspection of passthrough data
my @friends = log_trace {
'friends list being generated, data from first friend: ' .
Dumper($_[0]->TO_JSON)
} generate_friend_list();
If you want complete inspection of passthrough data, take a look at the "Dlog_$level" functions.
Which functions are exported depends on what was passed to "-levels". The default (no -levels
option passed) would export:
- log_trace
- log_debug
- log_info
- log_warn
- log_error
- log_fatal
logS_$level
Import Tag: :log
Arguments: CodeRef $returning_message, Item $arg
This is really just a special case of the "log_$level" functions. It forces scalar context when that is what you need. Other than that it works exactly same:
my $friend = logS_trace {
'I only have one friend: ' . Dumper($_[0]->TO_JSON)
} friend();
See also: "DlogS_$level".
Dlog_$level
Import Tag: :dlog
Arguments: CodeRef $returning_message, @args
All of the following six functions work the same as their "log_$level" brethren, except they return what is passed into them and put the stringified (with Data::Dumper::Concise) version of their args into $_
. This means you can do cool things like the following:
my @nicks = Dlog_debug { "names: $_" } map $_->value, $frew->names->all;
and the output might look something like:
names: "fREW"
"fRIOUX"
"fROOH"
"fRUE"
"fiSMBoC"
Which functions are exported depends on what was passed to "-levels". The default (no -levels
option passed) would export:
- Dlog_trace
- Dlog_debug
- Dlog_info
- Dlog_warn
- Dlog_error
- Dlog_fatal
DlogS_$level
Import Tag: :dlog
Arguments: CodeRef $returning_message, Item $arg
Like "logS_$level", these functions are a special case of "Dlog_$level". They only take a single scalar after the $returning_message
instead of slurping up (and also setting wantarray
) all the @args
my $pals_rs = DlogS_debug { "pals resultset: $_" }
$schema->resultset('Pals')->search({ perlers => 1 });
LOGGER CODEREF
Anywhere a logger object can be passed, a coderef is accepted. This is so that the user can use different logger objects based on runtime information. The logger coderef is passed the package of the caller the caller level the coderef needs to use if it wants more caller information. The latter is in a hashref to allow for more options in the future.
The following is an example that uses the information passed to the logger coderef. It sets the global logger to $l3
, the logger for the A1
package to $l1
, except the lol
method in A1
which uses the $l2
logger and lastly the logger for the A2
package to $l2
.
my $complex_dispatcher = do {
my $l1 = ...;
my $l2 = ...;
my $l3 = ...;
my %registry = (
-logger => $l3,
A1 => {
-logger => $l1,
lol => $l2,
},
A2 => { -logger => $l2 },
);
sub {
my ( $package, $info ) = @_;
my $logger = $registry{'-logger'};
if (my $r = $registry{$package}) {
$logger = $r->{'-logger'} if $r->{'-logger'};
my (undef, undef, undef, $sub) = caller($info->{caller_level});
$sub =~ s/^\Q$package\E:://g;
$logger = $r->{$sub} if $r->{$sub};
}
return $logger;
}
};
set_logger $complex_dispatcher;
LOGGER INTERFACE
Because this module is ultimately pretty looking glue (glittery?) with the awesome benefit of the Contextual part, users will often want to make their favorite logger work with it. The following are the methods that should be implemented in the logger:
is_trace
is_debug
is_info
is_warn
is_error
is_fatal
trace
debug
info
warn
error
fatal
The first six merely need to return true if that level is enabled. The latter six take the results of whatever the user returned from their coderef and log them. For a basic example see Log::Contextual::SimpleLogger.
AUTHOR
frew - Arthur Axel "fREW" Schmidt <frioux@gmail.com>
DESIGNER
mst - Matt S. Trout <mst@shadowcat.co.uk>
COPYRIGHT
Copyright (c) 2012 the Log::Contextual "AUTHOR" and "DESIGNER" as listed above.
LICENSE
This library is free software and may be distributed under the same terms as Perl 5 itself.