From: Arthur Axel 'fREW' Schmidt Date: Wed, 3 Mar 2010 03:45:33 +0000 (-0600) Subject: tests for -default_logger X-Git-Tag: v0.00200~6 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=3ccc9c473fae3fc33dc3863734c75fda552939d9;p=p5sagit%2FLog-Contextual.git tests for -default_logger --- diff --git a/lib/Log/Contextual.pm b/lib/Log/Contextual.pm index 1585db6..596c155 100644 --- a/lib/Log/Contextual.pm +++ b/lib/Log/Contextual.pm @@ -51,11 +51,12 @@ sub import { 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; } } @@ -65,7 +66,15 @@ sub import { 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; diff --git a/t/default_logger.t b/t/default_logger.t new file mode 100644 index 0000000..da46867 --- /dev/null +++ b/t/default_logger.t @@ -0,0 +1,57 @@ +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');