1package Plack::Middleware::Log4perl; 2use strict; 3use parent qw(Plack::Middleware); 4use Plack::Util::Accessor qw(category logger conf); 5use Carp (); 6 7sub prepare_app { 8 my $self = shift; 9 10 if ($self->conf) { 11 require Log::Log4perl; 12 Log::Log4perl::init($self->conf); 13 } 14 15 # NOTICE: if category = '0' you must not change it by '' (root logger) 16 $self->logger( Log::Log4perl->get_logger( defined $self->category ? $self->category : '' ) ); 17} 18 19sub call { 20 my($self, $env) = @_; 21 22 $env->{'psgix.logger'} = sub { 23 my $args = shift; 24 my $level = $args->{level}; 25 local $Log::Log4perl::caller_depth 26 = $Log::Log4perl::caller_depth + 1; 27 $self->logger->$level($args->{message}); 28 }; 29 30 $self->app->($env); 31} 32 331; 34 35__END__ 36 37=head1 NAME 38 39Plack::Middleware::Log4perl - Uses Log::Log4perl to configure logger 40 41=head1 SYNOPSIS 42 43 my $app = sub { 44 my $env = shift; 45 46 $env->{'psgix.logger'}({ level => 'error', message => 'Hi' }); 47 48 return [ 49 '200', 50 [ 'Content-Type' => 'text/plain' ], 51 [ "Hello World" ], 52 ]; 53 }; 54 55 56 # Use your own Log4perl configuration 57 use Log::Log4perl; 58 Log::Log4perl::init('/path/to/log4perl.conf'); 59 60 builder { 61 # tell the logger to log with 'plack' category 62 enable "Log4perl", category => "plack"; 63 $app; 64 } 65 66 67 # Configure with Log4perl middleware options 68 builder { 69 enable "Log4perl", category => "plack", conf => '/path/to/log4perl.conf'; 70 $app; 71 } 72 73=head1 DESCRIPTION 74 75Log4perl is a L<Plack::Middleware> component that allows you to use 76L<Log::Log4perl> to configure the logging object C<psgix.logger> for a 77given category. 78 79=head1 CONFIGURATION 80 81=over 4 82 83=item category 84 85The C<log4perl> category to send logs to. Defaults to C<''> which means 86it send to the root logger. 87 88=item conf 89 90The configuration file path (or a scalar ref containing the config 91string) for L<Log::Log4perl> to automatically configure. 92 93=back 94 95=head1 AUTHOR 96 97Tatsuhiko Miyagawa 98 99=head1 SEE ALSO 100 101L<Log::Log4perl> 102 103L<Plack::Middleware::LogDispatch> 104 105=cut 106 107