From: Arthur Axel 'fREW' Schmidt Date: Tue, 14 Sep 2010 20:30:11 +0000 (-0500) Subject: test of CatLogger idiom X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=a74cad5eacc812ef9060e8d60a2485c6c35a3086;p=p5sagit%2FLog-Contextual.git test of CatLogger idiom --- diff --git a/lib/Log/Contextual.pm b/lib/Log/Contextual.pm index 550804f..3f4c68e 100644 --- a/lib/Log/Contextual.pm +++ b/lib/Log/Contextual.pm @@ -51,6 +51,9 @@ sub import { } elsif ( $val eq '-logger' ) { set_logger($_[$idx + 1]); $skipnext = 1; + } elsif ( $val eq '-args' ) { + _set_package_logger_args_for(scalar caller, $_[$idx + 1]); + $skipnext = 1; } elsif ( $val eq '-package_logger' ) { _set_package_logger_for(scalar caller, $_[$idx + 1]); $skipnext = 1; @@ -71,6 +74,7 @@ sub import { our $Get_Logger; our %Default_Logger; our %Package_Logger; +our %Package_Logger_Args; sub _set_default_logger_for { my $logger = $_[1]; @@ -82,6 +86,13 @@ sub _set_default_logger_for { $Default_Logger{$_[0]} = $logger } +sub _set_package_logger_args_for { + my $args = $_[1]; + die 'args are not an arrayref. Please try again.' + unless ref $args eq 'ARRAY'; + $Package_Logger_Args{$_[0]} = $args +} + sub _set_package_logger_for { my $logger = $_[1]; if(ref $logger ne 'CODE') { @@ -99,7 +110,10 @@ sub _get_logger($) { $Get_Logger || $Default_Logger{$package} || die q( no logger set! you can't try to log something without a logger! ) - )->($package); + )->({ + package => $package, + args => $Package_Logger_Args{$package}, + }); } sub set_logger { diff --git a/t/category_idiom.t b/t/category_idiom.t new file mode 100644 index 0000000..c0a3599 --- /dev/null +++ b/t/category_idiom.t @@ -0,0 +1,53 @@ +use strict; +use warnings; + +use Test::More; + +my @out; + +# these shouldn't be packages, but I'm not sure how else I'm going to +# do it yet. + +{ + package CatLogger; + + use Log::Contextual::NullLogger; + use base 'Log::Contextual::SimpleLogger'; + + sub include_category { $_[1] eq 'awesome' } + + sub log_contextual_coderef { + my $logger = CatLogger->new({ levels_upto => 'trace', coderef => sub { push @out, $_[0] } }); + + return Log::Contextual::NullLogger->new + unless $logger->include_category($_[0]{args}[0]); + return $logger; + } + + 1; +} + +{ + package Foo; + + use Log::Contextual ':log', -args => ['lame'], + -package_logger => \&CatLogger::log_contextual_coderef; + + log_debug { 'test' }; +} + +ok @out == 0, 'no output because category is lame'; + +{ + package Bar; + use Log::Contextual::NullLogger; + + use Log::Contextual ':log', -args => ['awesome'], + -package_logger => \&CatLogger::log_contextual_coderef; + + log_debug { 'test' }; +} + +ok @out == 1, 'output because category is awesome'; + +done_testing;