| 1 |
package Lemonldap::NG::Common::Logger::Log4perl; |
| 2 |
|
| 3 |
use strict; |
| 4 |
use Log::Log4perl; |
| 5 |
use Log::Log4perl::MDC; |
| 6 |
|
| 7 |
our $VERSION = '2.23.0'; |
| 8 |
|
| 9 |
our $init = 0; |
| 10 |
|
| 11 |
sub new { |
| 12 |
my ( $class, $conf, %args ) = @_; |
| 13 |
my $self = bless {}, $class; |
| 14 |
|
| 15 |
unless ($init) { |
| 16 |
my $file = $conf->{log4perlConfFile} || '/etc/log4perl.conf'; |
| 17 |
|
| 18 |
# Fix reporting of code location |
| 19 |
Log::Log4perl->wrapper_register( |
| 20 |
"Lemonldap::NG::Common::Logger::_Duplicate"); |
| 21 |
Log::Log4perl->wrapper_register(__PACKAGE__); |
| 22 |
|
| 23 |
# map %S to the userData |
| 24 |
Log::Log4perl::Layout::PatternLayout::add_global_cspec( |
| 25 |
'S', |
| 26 |
sub { |
| 27 |
my $layout = shift; |
| 28 |
my $subvar = $layout->{curlies}; |
| 29 |
my $req = Log::Log4perl::MDC->get("req"); |
| 30 |
return defined($req) ? $req->userData->{$subvar} : undef; |
| 31 |
} |
| 32 |
); |
| 33 |
|
| 34 |
# map %E to the stored $req->env |
| 35 |
Log::Log4perl::Layout::PatternLayout::add_global_cspec( |
| 36 |
'E', |
| 37 |
sub { |
| 38 |
my $layout = shift; |
| 39 |
my $subvar = $layout->{curlies}; |
| 40 |
my $req = Log::Log4perl::MDC->get("req"); |
| 41 |
return defined($req) ? $req->env->{$subvar} : undef; |
| 42 |
} |
| 43 |
); |
| 44 |
|
| 45 |
# map %Q to the stored $req |
| 46 |
Log::Log4perl::Layout::PatternLayout::add_global_cspec( |
| 47 |
'Q', |
| 48 |
sub { |
| 49 |
my $layout = shift; |
| 50 |
my $subvar = $layout->{curlies}; |
| 51 |
my $req = Log::Log4perl::MDC->get("req"); |
| 52 |
if ( ref($req) and $req->can($subvar) ) { |
| 53 |
return $req->$subvar; |
| 54 |
} |
| 55 |
else { |
| 56 |
return undef; |
| 57 |
} |
| 58 |
} |
| 59 |
); |
| 60 |
Log::Log4perl->init($file); |
| 61 |
$init++; |
| 62 |
} |
| 63 |
my $logger = |
| 64 |
$args{user} |
| 65 |
? ( $conf->{log4perlUserLogger} || 'LLNG.user' ) |
| 66 |
: ( $conf->{log4perlLogger} || 'LLNG' ); |
| 67 |
$self->{log} = Log::Log4perl->get_logger($logger); |
| 68 |
|
| 69 |
no warnings 'redefine'; |
| 70 |
my $show = 1; |
| 71 |
|
| 72 |
foreach (qw(error warn notice info debug)) { |
| 73 |
if ($show) { |
| 74 |
my $name = $_; |
| 75 |
$name = 'info' if ( $_ eq 'notice' ); |
| 76 |
eval qq'sub $_ {shift->{log}->$name(\@_)}'; |
| 77 |
die $@ if ($@); |
| 78 |
} |
| 79 |
else { |
| 80 |
eval qq'sub $_ {1}'; |
| 81 |
} |
| 82 |
$show = 0 if ( $conf->{logLevel} eq $_ ); |
| 83 |
} |
| 84 |
die "Unknown logLevel $conf->{logLevel}" if $show; |
| 85 |
return $self; |
| 86 |
} |
| 87 |
|
| 88 |
sub setRequestObj { |
| 89 |
my ( $self, $req ) = @_; |
| 90 |
Log::Log4perl::MDC->put( "req", $req ); |
| 91 |
} |
| 92 |
|
| 93 |
sub clearRequestObj { |
| 94 |
my ( $self, $req ) = @_; |
| 95 |
my $text = Log::Log4perl::MDC->remove(); |
| 96 |
} |
| 97 |
|
| 98 |
1; |