unless @_;
for my $idx ( 0 .. $#_ ) {
- if ( $_[$idx] eq '-logger' ) {
+ my $val = $_[$idx];
+ if ( defined $val && $val eq '-logger' ) {
set_logger($_[$idx + 1]);
splice @_, $idx, 2;
- } elsif ( $_[$idx] eq '-default_logger' ) {
- set_default_logger_for(scalar caller, $_[$idx + 1]);
+ } elsif ( defined $val && $val eq '-default_logger' ) {
+ _set_default_logger_for(scalar caller, $_[$idx + 1]);
splice @_, $idx, 2;
}
}
our $Get_Logger;
our %Default_Logger;
-sub _set_default_logger_for { $Default_Logger{$_[0]} = $_[1] }
+sub _set_default_logger_for {
+ my $logger = $_[1];
+ if(ref $logger ne 'CODE') {
+ die 'logger was not a CodeRef or a logger object. Please try again.'
+ unless blessed($logger);
+ $logger = do { my $l = $logger; sub { $l } }
+ }
+ $Default_Logger{$_[0]} = $logger
+}
sub _get_logger($) {
my $package = shift;
--- /dev/null
+use strict;
+use warnings;
+
+use Log::Contextual qw{:log with_logger set_logger};
+use Log::Contextual::SimpleLogger;
+use Test::More qw(no_plan);
+my $var1;
+my $var2;
+my $var3;
+my $var_logger1 = Log::Contextual::SimpleLogger->new({
+ levels => [qw(trace debug info warn error fatal)],
+ coderef => sub { $var1 = shift },
+});
+my $var_logger2;
+BEGIN {
+ $var_logger2 = Log::Contextual::SimpleLogger->new({
+ levels => [qw(trace debug info warn error fatal)],
+ coderef => sub { $var2 = shift },
+ })
+}
+
+my $var_logger3;
+BEGIN {
+ $var_logger3 = Log::Contextual::SimpleLogger->new({
+ levels => [qw(trace debug info warn error fatal)],
+ coderef => sub { $var3 = shift },
+ })
+}
+
+{
+ package J;
+ use Log::Contextual qw{:log with_logger set_logger}, -default_logger => $var_logger3;
+
+ sub foo {
+ log_debug { 'bar' };
+ }
+}
+
+{
+ package K;
+ use Log::Contextual qw{:log with_logger set_logger}, -default_logger => $var_logger2;
+
+ sub foo {
+ log_debug { 'foo' };
+ }
+}
+J::foo;
+K::foo;
+
+is($var2, "[debug] foo\n", 'default_logger works for one package');
+is($var3, "[debug] bar\n", 'default_logger works for both packages');
+$var2 = '';
+set_logger($var_logger1);
+
+K::foo;
+is($var2, q(), '... but set_logger wins');
+is($var1, "[debug] foo\n", '... and gets the value');