File Coverage

blib/lib/Log/Log4perl.pm
Criterion Covered Total %
statement 230 253 90.9
branch 67 94 71.2
condition 8 21 38.1
subroutine 44 50 88.0
pod 2 22 9.0
total 351 440 79.7


line stmt bran cond sub pod time code
1             ##################################################
2             ##################################################
3              
4             END { local($?); Log::Log4perl::Logger::cleanup(); }
5 70     70   154153  
  70         425  
6             use 5.006;
7 70     75   5756391 use strict;
  70         906  
8 70     70   410 use warnings;
  70         148  
  70         1766  
9 70     70   414  
  70         171  
  70         2194  
10             use Carp;
11 70     70   420  
  70         173  
  70         5234  
12             use Log::Log4perl::Util;
13 70     70   33545 use Log::Log4perl::Logger;
  70         199  
  70         3385  
14 70     70   36397 use Log::Log4perl::Level;
  70         238  
  70         2385  
15 70     70   531 use Log::Log4perl::Config;
  70         150  
  70         437  
16 70     70   407 use Log::Log4perl::Appender;
  70         140  
  70         1416  
17 70     70   357  
  70         157  
  70         14678  
18             our $VERSION = '1.57';
19              
20             # set this to '1' if you're using a wrapper
21             # around Log::Log4perl
22             our $caller_depth = 0;
23              
24             #this is a mapping of convenience names to opcode masks used in
25             #$ALLOWED_CODE_OPS_IN_CONFIG_FILE below
26             our %ALLOWED_CODE_OPS = (
27             'safe' => [ ':browse' ],
28             'restrictive' => [ ':default' ],
29             );
30              
31             our %WRAPPERS_REGISTERED = map { $_ => 1 } qw(Log::Log4perl);
32              
33             #set this to the opcodes which are allowed when
34             #$ALLOW_CODE_IN_CONFIG_FILE is set to a true value
35             #if undefined, there are no restrictions on code that can be
36             #excuted
37             our @ALLOWED_CODE_OPS_IN_CONFIG_FILE;
38              
39             #this hash lists things that should be exported into the Safe
40             #compartment. The keys are the package the symbol should be
41             #exported from and the values are array references to the names
42             #of the symbols (including the leading type specifier)
43             our %VARS_SHARED_WITH_SAFE_COMPARTMENT = (
44             main => [ '%ENV' ],
45             );
46              
47             #setting this to a true value will allow Perl code to be executed
48             #within the config file. It works in conjunction with
49             #$ALLOWED_CODE_OPS_IN_CONFIG_FILE, which if defined restricts the
50             #opcodes which can be executed using the 'Safe' module.
51             #setting this to a false value disables code execution in the
52             #config file
53             our $ALLOW_CODE_IN_CONFIG_FILE = 1;
54              
55             #arrays in a log message will be joined using this character,
56             #see Log::Log4perl::Appender::DBI
57             our $JOIN_MSG_ARRAY_CHAR = '';
58              
59             #version required for XML::DOM, to enable XML Config parsing
60             #and XML Config unit tests
61             our $DOM_VERSION_REQUIRED = '1.29';
62              
63             our $CHATTY_DESTROY_METHODS = 0;
64              
65             our $LOGDIE_MESSAGE_ON_STDERR = 1;
66             our $LOGEXIT_CODE = 1;
67             our %IMPORT_CALLED;
68              
69             our $EASY_CLOSURES = {};
70              
71             # to throw refs as exceptions via logcarp/confess, turn this off
72             our $STRINGIFY_DIE_MESSAGE = 1;
73              
74             use constant _INTERNAL_DEBUG => 0;
75 70     70   565  
  70         162  
  70         12934  
76             ##################################################
77             ##################################################
78             my($class) = shift;
79              
80 85     85   114863 my $caller_pkg = caller();
81              
82 85         228 return 1 if $IMPORT_CALLED{$caller_pkg}++;
83              
84 85 100       606 my(%tags) = map { $_ => 1 } @_;
85              
86 84         207 # Lazy man's logger
  53         184  
87             if(exists $tags{':easy'}) {
88             $tags{':levels'} = 1;
89 84 100       310 $tags{':nowarn'} = 1;
90 27         63 $tags{'get_logger'} = 1;
91 27         53 }
92 27         49  
93             if(exists $tags{':no_extra_logdie_message'}) {
94             $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR = 0;
95 84 100       272 delete $tags{':no_extra_logdie_message'};
96 1         2 }
97 1         2  
98             if(exists $tags{get_logger}) {
99             # Export get_logger into the calling module's
100 84 100       243 no strict qw(refs);
101             *{"$caller_pkg\::get_logger"} = *get_logger;
102 70     70   555  
  70         185  
  70         8367  
103 42         92 delete $tags{get_logger};
  42         325  
104             }
105 42         109  
106             if(exists $tags{':levels'}) {
107             # Export log levels ($DEBUG, $INFO etc.) from Log4perl::Level
108 84 100       256 for my $key (keys %Log::Log4perl::Level::PRIORITY) {
109             my $name = "$caller_pkg\::$key";
110 30         136 # Need to split this up in two lines, or CVS will
111 240         439 # mess it up.
112             my $value = $Log::Log4perl::Level::PRIORITY{
113             $key};
114             no strict qw(refs);
115 240         357 *{"$name"} = \$value;
116 70     70   476 }
  70         165  
  70         159554  
117 240         314  
  240         857  
118             delete $tags{':levels'};
119             }
120 30         86  
121             # Lazy man's logger
122             if(exists $tags{':easy'}) {
123             delete $tags{':easy'};
124 84 100       318  
125 27         89 # Define default logger object in caller's package
126             my $logger = get_logger("$caller_pkg");
127            
128 27         96 # Define DEBUG, INFO, etc. routines in caller's package
129             for(qw(TRACE DEBUG INFO WARN ERROR FATAL ALWAYS)) {
130             my $level = $_;
131 27         69 $level = "OFF" if $level eq "ALWAYS";
132 189         293 my $lclevel = lc($_);
133 189 100       365 easy_closure_create($caller_pkg, $_, sub {
134 189         285 Log::Log4perl::Logger::init_warn() unless
135             $Log::Log4perl::Logger::INITIALIZED or
136 35 0 33 35   510 $Log::Log4perl::Logger::NON_INIT_WARNED;
137             $logger->{$level}->($logger, @_, $level);
138             }, $logger);
139 35         154 }
140 189         754  
141             # Define LOGCROAK, LOGCLUCK, etc. routines in caller's package
142             for(qw(LOGCROAK LOGCLUCK LOGCARP LOGCONFESS)) {
143             my $method = "Log::Log4perl::Logger::" . lc($_);
144 27         73  
145 108         308 easy_closure_create($caller_pkg, $_, sub {
146             unshift @_, $logger;
147             goto &$method;
148 5     5   1645 }, $logger);
149 5         51 }
150 108         510  
151             # Define LOGDIE, LOGWARN
152             easy_closure_create($caller_pkg, "LOGDIE", sub {
153             Log::Log4perl::Logger::init_warn() unless
154             $Log::Log4perl::Logger::INITIALIZED or
155 7 0 33 7   2991 $Log::Log4perl::Logger::NON_INIT_WARNED;
156             $logger->{FATAL}->($logger, @_, "FATAL");
157             $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR ?
158 7         33 CORE::die(Log::Log4perl::Logger::callerline(join '', @_)) :
159 7 50       45 exit $Log::Log4perl::LOGEXIT_CODE;
160             }, $logger);
161              
162 27         222 easy_closure_create($caller_pkg, "LOGEXIT", sub {
163             Log::Log4perl::Logger::init_warn() unless
164             $Log::Log4perl::Logger::INITIALIZED or
165 0 0 0 0   0 $Log::Log4perl::Logger::NON_INIT_WARNED;
166             $logger->{FATAL}->($logger, @_, "FATAL");
167             exit $Log::Log4perl::LOGEXIT_CODE;
168 0         0 }, $logger);
169 0         0  
170 27         161 easy_closure_create($caller_pkg, "LOGWARN", sub {
171             Log::Log4perl::Logger::init_warn() unless
172             $Log::Log4perl::Logger::INITIALIZED or
173 6 0 33 6   4652 $Log::Log4perl::Logger::NON_INIT_WARNED;
174             $logger->{WARN}->($logger, @_, "WARN");
175             CORE::warn(Log::Log4perl::Logger::callerline(join '', @_))
176 6         23 if $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR;
177 6 100       34 }, $logger);
178             }
179 27         121  
180             if(exists $tags{':nowarn'}) {
181             $Log::Log4perl::Logger::NON_INIT_WARNED = 1;
182 84 100       411 delete $tags{':nowarn'};
183 27         76 }
184 27         61  
185             if(exists $tags{':nostrict'}) {
186             $Log::Log4perl::Logger::NO_STRICT = 1;
187 84 100       266 delete $tags{':nostrict'};
188 1         2 }
189 1         2  
190             if(exists $tags{':resurrect'}) {
191             my $FILTER_MODULE = "Filter::Util::Call";
192 84 100       258 if(! Log::Log4perl::Util::module_available($FILTER_MODULE)) {
193 1         2 die "$FILTER_MODULE required with :resurrect" .
194 1 50       4 "(install from CPAN)";
195 0         0 }
196             eval "require $FILTER_MODULE" or die "Cannot pull in $FILTER_MODULE";
197             Filter::Util::Call::filter_add(
198 1 50       56 sub {
199             my($status);
200             s/^\s*###l4p// if
201 29     29   38 ($status = Filter::Util::Call::filter_read()) > 0;
202 29 100       122 $status;
203             });
204 29         1854 delete $tags{':resurrect'};
205 1         8 }
206 1         16  
207             if(keys %tags) {
208             # We received an Option we couldn't understand.
209 84 50       34596 die "Unknown Option(s): @{[keys %tags]}";
210             }
211 0         0 }
  0         0  
212              
213             ##################################################
214             ##################################################
215             return $Log::Log4perl::Logger::INITIALIZED;
216             }
217              
218 3     3 0 36 ##################################################
219             ##################################################
220             die "THIS CLASS ISN'T FOR DIRECT USE. " .
221             "PLEASE CHECK 'perldoc " . __PACKAGE__ . "'.";
222             }
223              
224 0     0 0 0 ##################################################
225             ##################################################
226             # Delegate this to the logger ...
227             return Log::Log4perl::Logger->reset();
228             }
229              
230             ##################################################
231             # called yet.
232 38     38 0 18576 ##################################################
233             init(@_) unless $Log::Log4perl::Logger::INITIALIZED;
234             }
235              
236             ##################################################
237             ##################################################
238             my($class, @args) = @_;
239 3 100   3 0 19  
240             #woops, they called ::init instead of ->init, let's be forgiving
241             if ($class ne __PACKAGE__) {
242             unshift(@args, $class);
243             }
244              
245 178     178 0 632529 # Delegate this to the config module
246             return Log::Log4perl::Config->init(@args);
247             }
248 178 100       703  
249 61         163 ##################################################
250             ##################################################
251             my($class, @args) = @_;
252              
253 178         1060 #woops, they called ::init instead of ->init, let's be forgiving
254             if ($class ne __PACKAGE__) {
255             unshift(@args, $class);
256             }
257              
258             # Delegate this to the config module
259 9     9 0 1390 return Log::Log4perl::Config->init_and_watch(@args);
260             }
261              
262 9 50       51  
263 0         0 ##################################################
264             ##################################################
265             my($class, @args) = @_;
266              
267 9         77 # Did somebody call us with Log::Log4perl::easy_init()?
268             if(ref($class) or $class =~ /^\d+$/) {
269             unshift @args, $class;
270             }
271              
272             # Reset everything first
273             Log::Log4perl->reset();
274 9     9 0 7130  
275             my @loggers = ();
276              
277 9 50 33     102 my %default = ( level => $DEBUG,
278 0         0 file => "STDERR",
279             utf8 => undef,
280             category => "",
281             layout => "%d %m%n",
282 9         37 );
283              
284 9         22 if(!@args) {
285             push @loggers, \%default;
286 9         55 } else {
287             for my $arg (@args) {
288             if($arg =~ /^\d+$/) {
289             my %logger = (%default, level => $arg);
290             push @loggers, \%logger;
291             } elsif(ref($arg) eq "HASH") {
292             my %logger = (%default, %$arg);
293 9 50       38 push @loggers, \%logger;
294 0         0 } else {
295             # I suggest this becomes a croak() after a
296 9         26 # reasonable deprecation cycle.
297 10 100       64 carp "All arguments to easy_init should be either "
    50          
298 4         27 . "an integer log level or a hash reference.";
299 4         21 }
300             }
301 6         39 }
302 6         27  
303             for my $logger (@loggers) {
304              
305             my $app;
306 0         0  
307             if($logger->{file} =~ /^stderr$/i) {
308             $app = Log::Log4perl::Appender->new(
309             "Log::Log4perl::Appender::Screen",
310             utf8 => $logger->{utf8});
311             } elsif($logger->{file} =~ /^stdout$/i) {
312 9         23 $app = Log::Log4perl::Appender->new(
313             "Log::Log4perl::Appender::Screen",
314 10         23 stderr => 0,
315             utf8 => $logger->{utf8});
316 10 100       64 } else {
    50          
317             my $binmode;
318             if($logger->{file} =~ s/^(:.*?)>/>/) {
319 6         39 $binmode = $1;
320             }
321             $logger->{file} =~ /^(>)?(>)?/;
322             my $mode = ($2 ? "append" : "write");
323             $logger->{file} =~ s/.*>+\s*//g;
324 0         0 $app = Log::Log4perl::Appender->new(
325             "Log::Log4perl::Appender::File",
326 4         7 filename => $logger->{file},
327 4 100       23 mode => $mode,
328 1         3 utf8 => $logger->{utf8},
329             binmode => $binmode,
330 4         24 );
331 4 100       22 }
332 4         28  
333             my $layout = Log::Log4perl::Layout::PatternLayout->new(
334             $logger->{layout});
335             $app->layout($layout);
336              
337             my $log = Log::Log4perl->get_logger($logger->{category});
338 4         29 $log->level($logger->{level});
339             $log->add_appender($app);
340             }
341              
342             $Log::Log4perl::Logger::INITIALIZED = 1;
343 10         75 }
344 10         46  
345             ##################################################
346 10         55 ##################################################
347 10         41 my $wrapper = $_[-1];
348 10         37  
349             $WRAPPERS_REGISTERED{ $wrapper } = 1;
350             }
351 9         51  
352             ##################################################
353             ##################################################
354             # get_logger() can be called in the following ways:
355             #
356             # (1) Log::Log4perl::get_logger() => ()
357 5     5 0 1889 # (2) Log::Log4perl->get_logger() => ("Log::Log4perl")
358             # (3) Log::Log4perl::get_logger($cat) => ($cat)
359 5         19 #
360             # (5) Log::Log4perl->get_logger($cat) => ("Log::Log4perl", $cat)
361             # (6) L4pSubclass->get_logger($cat) => ("L4pSubclass", $cat)
362              
363             # Note that (4) L4pSubclass->get_logger() => ("L4pSubclass")
364             # is indistinguishable from (3) and therefore can't be allowed.
365             # Wrapper classes always have to specify the category explicitly.
366              
367             my $category;
368              
369             if(@_ == 0) {
370             # 1
371             my $level = 0;
372             do { $category = scalar caller($level++);
373             } while exists $WRAPPERS_REGISTERED{ $category };
374              
375             } elsif(@_ == 1) {
376             # 2, 3
377             $category = $_[0];
378 251     251 0 2022938  
379             my $level = 0;
380 251 100       982 while(exists $WRAPPERS_REGISTERED{ $category }) {
    100          
381             $category = scalar caller($level++);
382 24         47 }
383 26         143  
384 24         47 } else {
385             # 5, 6
386             $category = $_[1];
387             }
388 126         270  
389             # Delegate this to the logger module
390 126         210 return Log::Log4perl::Logger->get_logger($category);
391 126         482 }
392 11         45  
393             ###########################################
394             ###########################################
395             my( $level ) = @_;
396              
397 101         205 my $category;
398              
399             {
400             my $category = scalar caller($level + 1);
401 251         1047  
402             if(defined $category and
403             exists $WRAPPERS_REGISTERED{ $category }) {
404             $level++;
405             redo;
406             }
407 370     370 0 715 }
408              
409 370         494 return $level;
410             }
411              
412 370         532 ##################################################
  373         872  
413             ##################################################
414 373 100 100     1687 return \%Log::Log4perl::Logger::APPENDER_BY_NAME;
415             }
416 3         7  
417 3         6 ##################################################
418             # it to a logger yet
419             ##################################################
420             my($class, $appender) = @_;
421 370         866  
422             my $name = $appender->name();
423             die "Mandatory parameter 'name' missing in appender" unless defined $name;
424              
425             # Make it known by name in the Log4perl universe
426             # (so that composite appenders can find it)
427 36     36 1 1384 Log::Log4perl->appenders()->{ $name } = $appender;
428             }
429              
430             ##################################################
431             # Return number of appenders changed
432             ##################################################
433             # If someone calls L4p-> and not L4p::
434 1     1 0 3 shift if $_[0] eq __PACKAGE__;
435             my($delta, $appenders) = @_;
436 1         4 my $retval = 0;
437 1 50       4  
438             if($delta == 0) {
439             # Nothing to do, no delta given.
440             return;
441 1         3 }
442              
443             if(defined $appenders) {
444             # Map names to objects
445             $appenders = [map {
446             die "Unkown appender: '$_'" unless exists
447             $Log::Log4perl::Logger::APPENDER_BY_NAME{
448             $_};
449 4 50   4 0 1075 $Log::Log4perl::Logger::APPENDER_BY_NAME{
450 4         9 $_}
451 4         8 } @$appenders];
452             } else {
453 4 50       10 # Just hand over all known appenders
454             $appenders = [values %{Log::Log4perl::appenders()}] unless
455 0         0 defined $appenders;
456             }
457              
458 4 100       11 # Change all appender thresholds;
459             foreach my $app (@$appenders) {
460             my $old_thres = $app->threshold();
461 1         4 my $new_thres;
462             if($delta > 0) {
463 1 50       3 $new_thres = Log::Log4perl::Level::get_higher_level(
464             $old_thres, $delta);
465 1         4 } else {
466             $new_thres = Log::Log4perl::Level::get_lower_level(
467             $old_thres, -$delta);
468             }
469 3 50       8  
  3         7  
470             ++$retval if ($app->threshold($new_thres) == $new_thres);
471             }
472             return $retval;
473             }
474 4         11  
475 5         14 ##################################################
476 5         7 ##################################################
477 5 100       13 # If someone calls L4p->appender_by_name and not L4p::appender_by_name
478 2         8 shift if $_[0] eq __PACKAGE__;
479              
480             my($name) = @_;
481 3         10  
482             if(defined $name and
483             exists $Log::Log4perl::Logger::APPENDER_BY_NAME{
484             $name}) {
485 5 50       13 return $Log::Log4perl::Logger::APPENDER_BY_NAME{
486             $name}->{appender};
487 4         22 } else {
488             return undef;
489             }
490             }
491              
492             ##################################################
493             ##################################################
494 1 50   1 0 12 # If someone calls L4p->... and not L4p::...
495             shift if $_[0] eq __PACKAGE__;
496 1         3 Log::Log4perl::Logger->eradicate_appender(@_);
497             }
498 1 50 33     7  
499             ##################################################
500             ##################################################
501             no warnings qw(redefine);
502 1         4  
503             my $l4p_wrapper = sub {
504 0         0 my($prio, @message) = @_;
505             local $Log::Log4perl::caller_depth =
506             $Log::Log4perl::caller_depth + 2;
507             get_logger(scalar caller(1))->log($prio, @message);
508             };
509              
510             *LWP::Debug::trace = sub {
511             $l4p_wrapper->($INFO, @_);
512 1 50   1 0 6 };
513 1         5 *LWP::Debug::conns =
514             *LWP::Debug::debug = sub {
515             $l4p_wrapper->($DEBUG, @_);
516             };
517             }
518              
519 70     70   640 ##################################################
  70         196  
  70         16413  
520             ##################################################
521             my($caller_pkg, $entry, $code, $logger) = @_;
522 0     0   0  
523 0         0 no strict 'refs';
524              
525 0         0 print("easy_closure: Setting shortcut $caller_pkg\::$entry ",
526 0     0 1 0 "(logger=$logger\n") if _INTERNAL_DEBUG;
527              
528             $EASY_CLOSURES->{ $caller_pkg }->{ $entry } = $logger;
529 0     0   0 *{"$caller_pkg\::$entry"} = $code;
530 0         0 }
531              
532             ###########################################
533 0     0   0 ###########################################
534 0         0 my($caller_pkg, $entry) = @_;
535              
536             no warnings 'redefine';
537             no strict 'refs';
538              
539             my $logger = $EASY_CLOSURES->{ $caller_pkg }->{ $entry };
540 378     378 0 716  
541             print("easy_closure: Nuking easy shortcut $caller_pkg\::$entry ",
542 70     70   613 "(logger=$logger\n") if _INTERNAL_DEBUG;
  70         184  
  70         9484  
543              
544 378         430 *{"$caller_pkg\::$entry"} = sub { };
545             delete $EASY_CLOSURES->{ $caller_pkg }->{ $entry };
546             }
547 378         775  
548 378         460 ##################################################
  378         1370  
549             ##################################################
550             my($caller_pkg) = @_;
551              
552             if(! exists $EASY_CLOSURES->{ $caller_pkg } ) {
553             return 1;
554 378     378 0 613 }
555              
556 70     70   585 for my $entry ( keys %{ $EASY_CLOSURES->{ $caller_pkg } } ) {
  70         153  
  70         3134  
557 70     70   465 easy_closure_cleanup( $caller_pkg, $entry );
  70         214  
  70         32336  
558             }
559 378         564  
560             delete $EASY_CLOSURES->{ $caller_pkg };
561 378         470 }
562              
563             ###########################################
564 378     1   1729 ###########################################
  378         1162  
565 378         795  
566             for my $caller_pkg ( keys %$EASY_CLOSURES ) {
567             easy_closure_category_cleanup( $caller_pkg );
568             }
569             }
570              
571 27     27 0 74 ###########################################
572             ###########################################
573 27 50       99 my($class, $logger) = @_;
574 0         0  
575             PKG: for my $caller_pkg ( keys %$EASY_CLOSURES ) {
576             for my $entry ( keys %{ $EASY_CLOSURES->{ $caller_pkg } } ) {
577 27         58 if( $logger == $EASY_CLOSURES->{ $caller_pkg }->{ $entry } ) {
  27         890  
578 378         622 easy_closure_category_cleanup( $caller_pkg );
579             next PKG;
580             }
581 27         136 }
582             }
583             }
584              
585             ##################################################
586             ##################################################
587             my ($class, $logger) = @_;
588 72     72 0 419  
589 26         82 # Any stealth logger convenience function still using it will
590             # now become a no-op.
591             Log::Log4perl->easy_closure_logger_remove( $logger );
592              
593             # Remove the logger from the system
594             # Need to split this up in two lines, or CVS will
595             # mess it up.
596 2     2 0 4 delete $Log::Log4perl::Logger::LOGGERS_BY_NAME->{
597             $logger->{category} };
598 2         8 }
599 2         5  
  2         11  
600 15 100       33 1;
601 1         4  
602 1         5  
603             =encoding utf8
604              
605             =head1 NAME
606              
607             Log::Log4perl - Log4j implementation for Perl
608              
609             =head1 SYNOPSIS
610            
611 2     2 0 612 # Easy mode if you like it simple ...
612              
613             use Log::Log4perl qw(:easy);
614             Log::Log4perl->easy_init($ERROR);
615 2         7  
616             DEBUG "This doesn't go anywhere";
617             ERROR "This gets logged";
618              
619             # ... or standard mode for more features:
620              
621 2         8 Log::Log4perl::init('/etc/log4perl.conf');
622            
623             --or--
624            
625             # Check config every 10 secs
626             Log::Log4perl::init_and_watch('/etc/log4perl.conf',10);
627              
628             --then--
629            
630             $logger = Log::Log4perl->get_logger('house.bedrm.desk.topdrwr');
631            
632             $logger->debug('this is a debug message');
633             $logger->info('this is an info message');
634             $logger->warn('etc');
635             $logger->error('..');
636             $logger->fatal('..');
637            
638             #####/etc/log4perl.conf###############################
639             log4perl.logger.house = WARN, FileAppndr1
640             log4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1
641            
642             log4perl.appender.FileAppndr1 = Log::Log4perl::Appender::File
643             log4perl.appender.FileAppndr1.filename = desk.log
644             log4perl.appender.FileAppndr1.layout = \
645             Log::Log4perl::Layout::SimpleLayout
646             ######################################################
647              
648             =head1 ABSTRACT
649              
650             Log::Log4perl provides a powerful logging API for your application
651              
652             =head1 DESCRIPTION
653              
654             Log::Log4perl lets you remote-control and fine-tune the logging behaviour
655             of your system from the outside. It implements the widely popular
656             (Java-based) Log4j logging package in pure Perl.
657              
658             B<For a detailed tutorial on Log::Log4perl usage, please read>
659              
660             L<http://www.perl.com/pub/a/2002/09/11/log4perl.html>
661              
662             Logging beats a debugger if you want to know what's going on
663             in your code during runtime. However, traditional logging packages
664             are too static and generate a flood of log messages in your log files
665             that won't help you.
666              
667             C<Log::Log4perl> is different. It allows you to control the number of
668             logging messages generated at three different levels:
669              
670             =over 4
671              
672             =item *
673              
674             At a central location in your system (either in a configuration file or
675             in the startup code) you specify I<which components> (classes, functions)
676             of your system should generate logs.
677              
678             =item *
679              
680             You specify how detailed the logging of these components should be by
681             specifying logging I<levels>.
682              
683             =item *
684              
685             You also specify which so-called I<appenders> you want to feed your
686             log messages to ("Print it to the screen and also append it to /tmp/my.log")
687             and which format ("Write the date first, then the file name and line
688             number, and then the log message") they should be in.
689              
690             =back
691              
692             This is a very powerful and flexible mechanism. You can turn on and off
693             your logs at any time, specify the level of detail and make that
694             dependent on the subsystem that's currently executed.
695              
696             Let me give you an example: You might
697             find out that your system has a problem in the
698             C<MySystem::Helpers::ScanDir>
699             component. Turning on detailed debugging logs all over the system would
700             generate a flood of useless log messages and bog your system down beyond
701             recognition. With C<Log::Log4perl>, however, you can tell the system:
702             "Continue to log only severe errors to the log file. Open a second
703             log file, turn on full debug logs in the C<MySystem::Helpers::ScanDir>
704             component and dump all messages originating from there into the new
705             log file". And all this is possible by just changing the parameters
706             in a configuration file, which your system can re-read even
707             while it's running!
708              
709             =head1 How to use it
710              
711             The C<Log::Log4perl> package can be initialized in two ways: Either
712             via Perl commands or via a C<log4j>-style configuration file.
713              
714             =head2 Initialize via a configuration file
715              
716             This is the easiest way to prepare your system for using
717             C<Log::Log4perl>. Use a configuration file like this:
718              
719             ############################################################
720             # A simple root logger with a Log::Log4perl::Appender::File
721             # file appender in Perl.
722             ############################################################
723             log4perl.rootLogger=ERROR, LOGFILE
724            
725             log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
726             log4perl.appender.LOGFILE.filename=/var/log/myerrs.log
727             log4perl.appender.LOGFILE.mode=append
728            
729             log4perl.appender.LOGFILE.layout=PatternLayout
730             log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n
731              
732             These lines define your standard logger that's appending severe
733             errors to C</var/log/myerrs.log>, using the format
734              
735             [millisecs] source-filename line-number class - message newline
736              
737             Assuming that this configuration file is saved as C<log.conf>, you need to
738             read it in the startup section of your code, using the following
739             commands:
740              
741             use Log::Log4perl;
742             Log::Log4perl->init("log.conf");
743              
744             After that's done I<somewhere> in the code, you can retrieve
745             logger objects I<anywhere> in the code. Note that
746             there's no need to carry any logger references around with your
747             functions and methods. You can get a logger anytime via a singleton
748             mechanism:
749              
750             package My::MegaPackage;
751             use Log::Log4perl;
752              
753             sub some_method {
754             my($param) = @_;
755              
756             my $log = Log::Log4perl->get_logger("My::MegaPackage");
757              
758             $log->debug("Debug message");
759             $log->info("Info message");
760             $log->error("Error message");
761              
762             ...
763             }
764              
765             With the configuration file above, C<Log::Log4perl> will write
766             "Error message" to the specified log file, but won't do anything for
767             the C<debug()> and C<info()> calls, because the log level has been set
768             to C<ERROR> for all components in the first line of
769             configuration file shown above.
770              
771             Why C<Log::Log4perl-E<gt>get_logger> and
772             not C<Log::Log4perl-E<gt>new>? We don't want to create a new
773             object every time. Usually in OO-Programming, you create an object
774             once and use the reference to it to call its methods. However,
775             this requires that you pass around the object to all functions
776             and the last thing we want is pollute each and every function/method
777             we're using with a handle to the C<Logger>:
778              
779             sub function { # Brrrr!!
780             my($logger, $some, $other, $parameters) = @_;
781             }
782              
783             Instead, if a function/method wants a reference to the logger, it
784             just calls the Logger's static C<get_logger($category)> method to obtain
785             a reference to the I<one and only> possible logger object of
786             a certain category.
787             That's called a I<singleton> if you're a Gamma fan.
788              
789             How does the logger know
790             which messages it is supposed to log and which ones to suppress?
791             C<Log::Log4perl> works with inheritance: The config file above didn't
792             specify anything about C<My::MegaPackage>.
793             And yet, we've defined a logger of the category
794             C<My::MegaPackage>.
795             In this case, C<Log::Log4perl> will walk up the namespace hierarchy
796             (C<My> and then we're at the root) to figure out if a log level is
797             defined somewhere. In the case above, the log level at the root
798             (root I<always> defines a log level, but not necessarily an appender)
799             defines that
800             the log level is supposed to be C<ERROR> -- meaning that I<DEBUG>
801             and I<INFO> messages are suppressed. Note that this 'inheritance' is
802             unrelated to Perl's class inheritance, it is merely related to the
803             logger namespace.
804             By the way, if you're ever in doubt about what a logger's category is,
805             use C<$logger-E<gt>category()> to retrieve it.
806              
807             =head2 Log Levels
808              
809             There are six predefined log levels: C<FATAL>, C<ERROR>, C<WARN>, C<INFO>,
810             C<DEBUG>, and C<TRACE> (in descending priority). Your configured logging level
811             has to at least match the priority of the logging message.
812              
813             If your configured logging level is C<WARN>, then messages logged
814             with C<info()>, C<debug()>, and C<trace()> will be suppressed.
815             C<fatal()>, C<error()> and C<warn()> will make their way through,
816             because their priority is higher or equal than the configured setting.
817              
818             Instead of calling the methods
819              
820             $logger->trace("..."); # Log a trace message
821             $logger->debug("..."); # Log a debug message
822             $logger->info("..."); # Log a info message
823             $logger->warn("..."); # Log a warn message
824             $logger->error("..."); # Log a error message
825             $logger->fatal("..."); # Log a fatal message
826              
827             you could also call the C<log()> method with the appropriate level
828             using the constants defined in C<Log::Log4perl::Level>:
829              
830             use Log::Log4perl::Level;
831              
832             $logger->log($TRACE, "...");
833             $logger->log($DEBUG, "...");
834             $logger->log($INFO, "...");
835             $logger->log($WARN, "...");
836             $logger->log($ERROR, "...");
837             $logger->log($FATAL, "...");
838              
839             This form is rarely used, but it comes in handy if you want to log
840             at different levels depending on an exit code of a function:
841              
842             $logger->log( $exit_level{ $rc }, "...");
843              
844             As for needing more logging levels than these predefined ones: It's
845             usually best to steer your logging behaviour via the category
846             mechanism instead.
847              
848             If you need to find out if the currently configured logging
849             level would allow a logger's logging statement to go through, use the
850             logger's C<is_I<level>()> methods:
851              
852             $logger->is_trace() # True if trace messages would go through
853             $logger->is_debug() # True if debug messages would go through
854             $logger->is_info() # True if info messages would go through
855             $logger->is_warn() # True if warn messages would go through
856             $logger->is_error() # True if error messages would go through
857             $logger->is_fatal() # True if fatal messages would go through
858              
859             Example: C<$logger-E<gt>is_warn()> returns true if the logger's current
860             level, as derived from either the logger's category (or, in absence of
861             that, one of the logger's parent's level setting) is
862             C<$WARN>, C<$ERROR> or C<$FATAL>.
863              
864             Also available are a series of more Java-esque functions which return
865             the same values. These are of the format C<isI<Level>Enabled()>,
866             so C<$logger-E<gt>isDebugEnabled()> is synonymous to
867             C<$logger-E<gt>is_debug()>.
868              
869              
870             These level checking functions
871             will come in handy later, when we want to block unnecessary
872             expensive parameter construction in case the logging level is too
873             low to log the statement anyway, like in:
874              
875             if($logger->is_error()) {
876             $logger->error("Erroneous array: @super_long_array");
877             }
878              
879             If we had just written
880              
881             $logger->error("Erroneous array: @super_long_array");
882              
883             then Perl would have interpolated
884             C<@super_long_array> into the string via an expensive operation
885             only to figure out shortly after that the string can be ignored
886             entirely because the configured logging level is lower than C<$ERROR>.
887              
888             The to-be-logged
889             message passed to all of the functions described above can
890             consist of an arbitrary number of arguments, which the logging functions
891             just chain together to a single string. Therefore
892              
893             $logger->debug("Hello ", "World", "!"); # and
894             $logger->debug("Hello World!");
895              
896             are identical.
897              
898             Note that even if one of the methods above returns true, it doesn't
899             necessarily mean that the message will actually get logged.
900             What is_debug() checks is that
901             the logger used is configured to let a message of the given priority
902             (DEBUG) through. But after this check, Log4perl will eventually apply custom
903             filters and forward the message to one or more appenders. None of this
904             gets checked by is_xxx(), for the simple reason that it's
905             impossible to know what a custom filter does with a message without
906             having the actual message or what an appender does to a message without
907             actually having it log it.
908              
909             =head2 Log and die or warn
910              
911             Often, when you croak / carp / warn / die, you want to log those messages.
912             Rather than doing the following:
913              
914             $logger->fatal($err) && die($err);
915              
916             you can use the following:
917              
918             $logger->logdie($err);
919              
920             And if instead of using
921              
922             warn($message);
923             $logger->warn($message);
924              
925             to both issue a warning via Perl's warn() mechanism and make sure you have
926             the same message in the log file as well, use:
927              
928             $logger->logwarn($message);
929              
930             Since there is
931             an ERROR level between WARN and FATAL, there are two additional helper
932             functions in case you'd like to use ERROR for either warn() or die():
933              
934             $logger->error_warn();
935             $logger->error_die();
936              
937             Finally, there's the Carp functions that, in addition to logging,
938             also pass the stringified message to their companions in the Carp package:
939              
940             $logger->logcarp(); # warn w/ 1-level stack trace
941             $logger->logcluck(); # warn w/ full stack trace
942             $logger->logcroak(); # die w/ 1-level stack trace
943             $logger->logconfess(); # die w/ full stack trace
944              
945             =head2 Appenders
946              
947             If you don't define any appenders, nothing will happen. Appenders will
948             be triggered whenever the configured logging level requires a message
949             to be logged and not suppressed.
950              
951             C<Log::Log4perl> doesn't define any appenders by default, not even the root
952             logger has one.
953              
954             C<Log::Log4perl> already comes with a standard set of appenders:
955              
956             Log::Log4perl::Appender::Screen
957             Log::Log4perl::Appender::ScreenColoredLevels
958             Log::Log4perl::Appender::File
959             Log::Log4perl::Appender::Socket
960             Log::Log4perl::Appender::DBI
961             Log::Log4perl::Appender::Synchronized
962             Log::Log4perl::Appender::RRDs
963              
964             to log to the screen, to files and to databases.
965              
966             On CPAN, you can find additional appenders like
967              
968             Log::Log4perl::Layout::XMLLayout
969              
970             by Guido Carls E<lt>gcarls@cpan.orgE<gt>.
971             It allows for hooking up Log::Log4perl with the graphical Log Analyzer
972             Chainsaw (see
973             L<Log::Log4perl::FAQ/"Can I use Log::Log4perl with log4j's Chainsaw?">).
974              
975             =head2 Additional Appenders via Log::Dispatch
976              
977             C<Log::Log4perl> also supports I<Dave Rolskys> excellent C<Log::Dispatch>
978             framework which implements a wide variety of different appenders.
979              
980             Here's the list of appender modules currently available via C<Log::Dispatch>:
981              
982             Log::Dispatch::ApacheLog
983             Log::Dispatch::DBI (by Tatsuhiko Miyagawa)
984             Log::Dispatch::Email,
985             Log::Dispatch::Email::MailSend,
986             Log::Dispatch::Email::MailSendmail,
987             Log::Dispatch::Email::MIMELite
988             Log::Dispatch::File
989             Log::Dispatch::FileRotate (by Mark Pfeiffer)
990             Log::Dispatch::Handle
991             Log::Dispatch::Screen
992             Log::Dispatch::Syslog
993             Log::Dispatch::Tk (by Dominique Dumont)
994              
995             Please note that in order to use any of these additional appenders, you
996             have to fetch Log::Dispatch from CPAN and install it. Also the particular
997             appender you're using might require installing the particular module.
998              
999             For additional information on appenders, please check the
1000             L<Log::Log4perl::Appender> manual page.
1001              
1002             =head2 Appender Example
1003              
1004             Now let's assume that we want to log C<info()> or
1005             higher prioritized messages in the C<Foo::Bar> category
1006             to both STDOUT and to a log file, say C<test.log>.
1007             In the initialization section of your system,
1008             just define two appenders using the readily available
1009             C<Log::Log4perl::Appender::File> and C<Log::Log4perl::Appender::Screen>
1010             modules:
1011              
1012             use Log::Log4perl;
1013              
1014             # Configuration in a string ...
1015             my $conf = q(
1016             log4perl.category.Foo.Bar = INFO, Logfile, Screen
1017              
1018             log4perl.appender.Logfile = Log::Log4perl::Appender::File
1019             log4perl.appender.Logfile.filename = test.log
1020             log4perl.appender.Logfile.layout = Log::Log4perl::Layout::PatternLayout
1021             log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n
1022              
1023             log4perl.appender.Screen = Log::Log4perl::Appender::Screen
1024             log4perl.appender.Screen.stderr = 0
1025             log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
1026             );
1027              
1028             # ... passed as a reference to init()
1029             Log::Log4perl::init( \$conf );
1030              
1031             Once the initialization shown above has happened once, typically in
1032             the startup code of your system, just use the defined logger anywhere in
1033             your system:
1034              
1035             ##########################
1036             # ... in some function ...
1037             ##########################
1038             my $log = Log::Log4perl::get_logger("Foo::Bar");
1039              
1040             # Logs both to STDOUT and to the file test.log
1041             $log->info("Important Info!");
1042              
1043             The C<layout> settings specified in the configuration section define the
1044             format in which the
1045             message is going to be logged by the specified appender. The format shown
1046             for the file appender is logging not only the message but also the number of
1047             milliseconds since the program has started (%r), the name of the file
1048             the call to the logger has happened and the line number there (%F and
1049             %L), the message itself (%m) and a OS-specific newline character (%n):
1050              
1051             [187] ./myscript.pl 27 Important Info!
1052              
1053             The
1054             screen appender above, on the other hand,
1055             uses a C<SimpleLayout>, which logs the
1056             debug level, a hyphen (-) and the log message:
1057              
1058             INFO - Important Info!
1059              
1060             For more detailed info on layout formats, see L<Log Layouts>.
1061              
1062             In the configuration sample above, we chose to define a I<category>
1063             logger (C<Foo::Bar>).
1064             This will cause only messages originating from
1065             this specific category logger to be logged in the defined format
1066             and locations.
1067              
1068             =head2 Logging newlines
1069              
1070             There's some controversy between different logging systems as to when and
1071             where newlines are supposed to be added to logged messages.
1072              
1073             The Log4perl way is that a logging statement I<should not>
1074             contain a newline:
1075              
1076             $logger->info("Some message");
1077             $logger->info("Another message");
1078              
1079             If this is supposed to end up in a log file like
1080              
1081             Some message
1082             Another message
1083              
1084             then an appropriate appender layout like "%m%n" will take care of adding
1085             a newline at the end of each message to make sure every message is
1086             printed on its own line.
1087              
1088             Other logging systems, Log::Dispatch in particular, recommend adding the
1089             newline to the log statement. This doesn't work well, however, if you, say,
1090             replace your file appender by a database appender, and all of a sudden
1091             those newlines scattered around the code don't make sense anymore.
1092              
1093             Assigning matching layouts to different appenders and leaving newlines
1094             out of the code solves this problem. If you inherited code that has logging
1095             statements with newlines and want to make it work with Log4perl, read
1096             the L<Log::Log4perl::Layout::PatternLayout> documentation on how to
1097             accomplish that.
1098              
1099             =head2 Configuration files
1100              
1101             As shown above, you can define C<Log::Log4perl> loggers both from within
1102             your Perl code or from configuration files. The latter have the unbeatable
1103             advantage that you can modify your system's logging behaviour without
1104             interfering with the code at all. So even if your code is being run by
1105             somebody who's totally oblivious to Perl, they still can adapt the
1106             module's logging behaviour to their needs.
1107              
1108             C<Log::Log4perl> has been designed to understand C<Log4j> configuration
1109             files -- as used by the original Java implementation. Instead of
1110             reiterating the format description in [2], let me just list three
1111             examples (also derived from [2]), which should also illustrate
1112             how it works:
1113              
1114             log4j.rootLogger=DEBUG, A1
1115             log4j.appender.A1=org.apache.log4j.ConsoleAppender
1116             log4j.appender.A1.layout=org.apache.log4j.PatternLayout
1117             log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n
1118              
1119             This enables messages of priority C<DEBUG> or higher in the root
1120             hierarchy and has the system write them to the console.
1121             C<ConsoleAppender> is a Java appender, but C<Log::Log4perl> jumps
1122             through a significant number of hoops internally to map these to their
1123             corresponding Perl classes, C<Log::Log4perl::Appender::Screen> in this case.
1124              
1125             Second example:
1126              
1127             log4perl.rootLogger=DEBUG, A1
1128             log4perl.appender.A1=Log::Log4perl::Appender::Screen
1129             log4perl.appender.A1.layout=PatternLayout
1130             log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n
1131             log4perl.logger.com.foo=WARN
1132              
1133             This defines two loggers: The root logger and the C<com.foo> logger.
1134             The root logger is easily triggered by debug-messages,
1135             but the C<com.foo> logger makes sure that messages issued within
1136             the C<Com::Foo> component and below are only forwarded to the appender
1137             if they're of priority I<warning> or higher.
1138              
1139             Note that the C<com.foo> logger doesn't define an appender. Therefore,
1140             it will just propagate the message up the hierarchy until the root logger
1141             picks it up and forwards it to the one and only appender of the root
1142             category, using the format defined for it.
1143              
1144             Third example:
1145              
1146             log4j.rootLogger=DEBUG, stdout, R
1147             log4j.appender.stdout=org.apache.log4j.ConsoleAppender
1148             log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
1149             log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n
1150             log4j.appender.R=org.apache.log4j.RollingFileAppender
1151             log4j.appender.R.File=example.log
1152             log4j.appender.R.layout=org.apache.log4j.PatternLayout
1153             log4j.appender.R.layout.ConversionPattern=%p %c - %m%n
1154              
1155             The root logger defines two appenders here: C<stdout>, which uses
1156             C<org.apache.log4j.ConsoleAppender> (ultimately mapped by C<Log::Log4perl>
1157             to L<Log::Log4perl::Appender::Screen>) to write to the screen. And
1158             C<R>, a C<org.apache.log4j.RollingFileAppender>
1159             (mapped by C<Log::Log4perl> to
1160             L<Log::Dispatch::FileRotate> with the C<File> attribute specifying the
1161             log file.
1162              
1163             See L<Log::Log4perl::Config> for more examples and syntax explanations.
1164              
1165             =head2 Log Layouts
1166              
1167             If the logging engine passes a message to an appender, because it thinks
1168             it should be logged, the appender doesn't just
1169             write it out haphazardly. There's ways to tell the appender how to format
1170             the message and add all sorts of interesting data to it: The date and
1171             time when the event happened, the file, the line number, the
1172             debug level of the logger and others.
1173              
1174             There's currently two layouts defined in C<Log::Log4perl>:
1175             C<Log::Log4perl::Layout::SimpleLayout> and
1176             C<Log::Log4perl::Layout::PatternLayout>:
1177              
1178             =over 4
1179              
1180             =item C<Log::Log4perl::SimpleLayout>
1181              
1182             formats a message in a simple
1183             way and just prepends it by the debug level and a hyphen:
1184             C<"$level - $message>, for example C<"FATAL - Can't open password file">.
1185              
1186             =item C<Log::Log4perl::Layout::PatternLayout>
1187              
1188             on the other hand is very powerful and
1189             allows for a very flexible format in C<printf>-style. The format
1190             string can contain a number of placeholders which will be
1191             replaced by the logging engine when it's time to log the message:
1192              
1193             %c Category of the logging event.
1194             %C Fully qualified package (or class) name of the caller
1195             %d Current date in yyyy/MM/dd hh:mm:ss format
1196             %F File where the logging event occurred
1197             %H Hostname (if Sys::Hostname is available)
1198             %l Fully qualified name of the calling method followed by the
1199             callers source the file name and line number between
1200             parentheses.
1201             %L Line number within the file where the log statement was issued
1202             %m The message to be logged
1203             %m{chomp} The message to be logged, stripped off a trailing newline
1204             %M Method or function where the logging request was issued
1205             %n Newline (OS-independent)
1206             %p Priority of the logging event
1207             %P pid of the current process
1208             %r Number of milliseconds elapsed from program start to logging
1209             event
1210             %R Number of milliseconds elapsed from last logging event to
1211             current logging event
1212             %T A stack trace of functions called
1213             %x The topmost NDC (see below)
1214             %X{key} The entry 'key' of the MDC (see below)
1215             %% A literal percent (%) sign
1216              
1217             NDC and MDC are explained in L<"Nested Diagnostic Context (NDC)">
1218             and L<"Mapped Diagnostic Context (MDC)">.
1219              
1220             Also, C<%d> can be fine-tuned to display only certain characteristics
1221             of a date, according to the SimpleDateFormat in the Java World
1222             (L<http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html>)
1223              
1224             In this way, C<%d{HH:mm}> displays only hours and minutes of the current date,
1225             while C<%d{yy, EEEE}> displays a two-digit year, followed by a spelled-out day
1226             (like C<Wednesday>).
1227              
1228             Similar options are available for shrinking the displayed category or
1229             limit file/path components, C<%F{1}> only displays the source file I<name>
1230             without any path components while C<%F> logs the full path. %c{2} only
1231             logs the last two components of the current category, C<Foo::Bar::Baz>
1232             becomes C<Bar::Baz> and saves space.
1233              
1234             If those placeholders aren't enough, then you can define your own right in
1235             the config file like this:
1236              
1237             log4perl.PatternLayout.cspec.U = sub { return "UID $<" }
1238              
1239             See L<Log::Log4perl::Layout::PatternLayout> for further details on
1240             customized specifiers.
1241              
1242             Please note that the subroutines you're defining in this way are going
1243             to be run in the C<main> namespace, so be sure to fully qualify functions
1244             and variables if they're located in different packages.
1245              
1246             SECURITY NOTE: this feature means arbitrary perl code can be embedded in the
1247             config file. In the rare case where the people who have access to your config
1248             file are different from the people who write your code and shouldn't have
1249             execute rights, you might want to call
1250              
1251             Log::Log4perl::Config->allow_code(0);
1252              
1253             before you call init(). Alternatively you can supply a restricted set of
1254             Perl opcodes that can be embedded in the config file as described in
1255             L<"Restricting what Opcodes can be in a Perl Hook">.
1256              
1257             =back
1258              
1259             All placeholders are quantifiable, just like in I<printf>. Following this
1260             tradition, C<%-20c> will reserve 20 chars for the category and left-justify it.
1261              
1262             For more details on logging and how to use the flexible and the simple
1263             format, check out the original C<log4j> website under
1264              
1265             L<SimpleLayout|http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/SimpleLayout.html>
1266             and
1267             L<PatternLayout|http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html>
1268              
1269             =head2 Penalties
1270              
1271             Logging comes with a price tag. C<Log::Log4perl> has been optimized
1272             to allow for maximum performance, both with logging enabled and disabled.
1273              
1274             But you need to be aware that there's a small hit every time your code
1275             encounters a log statement -- no matter if logging is enabled or not.
1276             C<Log::Log4perl> has been designed to keep this so low that it will
1277             be unnoticeable to most applications.
1278              
1279             Here's a couple of tricks which help C<Log::Log4perl> to avoid
1280             unnecessary delays:
1281              
1282             You can save serious time if you're logging something like
1283              
1284             # Expensive in non-debug mode!
1285             for (@super_long_array) {
1286             $logger->debug("Element: $_");
1287             }
1288              
1289             and C<@super_long_array> is fairly big, so looping through it is pretty
1290             expensive. Only you, the programmer, knows that going through that C<for>
1291             loop can be skipped entirely if the current logging level for the
1292             actual component is higher than C<debug>.
1293             In this case, use this instead:
1294              
1295             # Cheap in non-debug mode!
1296             if($logger->is_debug()) {
1297             for (@super_long_array) {
1298             $logger->debug("Element: $_");
1299             }
1300             }
1301              
1302             If you're afraid that generating the parameters to the
1303             logging function is fairly expensive, use closures:
1304              
1305             # Passed as subroutine ref
1306             use Data::Dumper;
1307             $logger->debug(sub { Dumper($data) } );
1308              
1309             This won't unravel C<$data> via Dumper() unless it's actually needed
1310             because it's logged.
1311              
1312             Also, Log::Log4perl lets you specify arguments
1313             to logger functions in I<message output filter syntax>:
1314              
1315             $logger->debug("Structure: ",
1316             { filter => \&Dumper,
1317             value => $someref });
1318              
1319             In this way, shortly before Log::Log4perl sending the
1320             message out to any appenders, it will be searching all arguments for
1321             hash references and treat them in a special way:
1322              
1323             It will invoke the function given as a reference with the C<filter> key
1324             (C<Data::Dumper::Dumper()>) and pass it the value that came with
1325             the key named C<value> as an argument.
1326             The anonymous hash in the call above will be replaced by the return
1327             value of the filter function.
1328              
1329             =head1 Categories
1330              
1331             B<Categories are also called "Loggers" in Log4perl, both refer
1332             to the same thing and these terms are used interchangeably.>
1333             C<Log::Log4perl> uses I<categories> to determine if a log statement in
1334             a component should be executed or suppressed at the current logging level.
1335             Most of the time, these categories are just the classes the log statements
1336             are located in:
1337              
1338             package Candy::Twix;
1339              
1340             sub new {
1341             my $logger = Log::Log4perl->get_logger("Candy::Twix");
1342             $logger->debug("Creating a new Twix bar");
1343             bless {}, shift;
1344             }
1345            
1346             # ...
1347              
1348             package Candy::Snickers;
1349              
1350             sub new {
1351             my $logger = Log::Log4perl->get_logger("Candy.Snickers");
1352             $logger->debug("Creating a new Snickers bar");
1353             bless {}, shift;
1354             }
1355              
1356             # ...
1357              
1358             package main;
1359             Log::Log4perl->init("mylogdefs.conf");
1360              
1361             # => "LOG> Creating a new Snickers bar"
1362             my $first = Candy::Snickers->new();
1363             # => "LOG> Creating a new Twix bar"
1364             my $second = Candy::Twix->new();
1365              
1366             Note that you can separate your category hierarchy levels
1367             using either dots like
1368             in Java (.) or double-colons (::) like in Perl. Both notations
1369             are equivalent and are handled the same way internally.
1370              
1371             However, categories are just there to make
1372             use of inheritance: if you invoke a logger in a sub-category,
1373             it will bubble up the hierarchy and call the appropriate appenders.
1374             Internally, categories are not related to the class hierarchy of the program
1375             at all -- they're purely virtual. You can use arbitrary categories --
1376             for example in the following program, which isn't oo-style, but
1377             procedural:
1378              
1379             sub print_portfolio {
1380              
1381             my $log = Log::Log4perl->get_logger("user.portfolio");
1382             $log->debug("Quotes requested: @_");
1383              
1384             for(@_) {
1385             print "$_: ", get_quote($_), "\n";
1386             }
1387             }
1388              
1389             sub get_quote {
1390              
1391             my $log = Log::Log4perl->get_logger("internet.quotesystem");
1392             $log->debug("Fetching quote: $_[0]");
1393              
1394             return yahoo_quote($_[0]);
1395             }
1396              
1397             The logger in first function, C<print_portfolio>, is assigned the
1398             (virtual) C<user.portfolio> category. Depending on the C<Log4perl>
1399             configuration, this will either call a C<user.portfolio> appender,
1400             a C<user> appender, or an appender assigned to root -- without
1401             C<user.portfolio> having any relevance to the class system used in
1402             the program.
1403             The logger in the second function adheres to the
1404             C<internet.quotesystem> category -- again, maybe because it's bundled
1405             with other Internet functions, but not because there would be
1406             a class of this name somewhere.
1407              
1408             However, be careful, don't go overboard: if you're developing a system
1409             in object-oriented style, using the class hierarchy is usually your best
1410             choice. Think about the people taking over your code one day: The
1411             class hierarchy is probably what they know right up front, so it's easy
1412             for them to tune the logging to their needs.
1413              
1414             =head2 Turn off a component
1415              
1416             C<Log4perl> doesn't only allow you to selectively switch I<on> a category
1417             of log messages, you can also use the mechanism to selectively I<disable>
1418             logging in certain components whereas logging is kept turned on in higher-level
1419             categories. This mechanism comes in handy if you find that while bumping
1420             up the logging level of a high-level (i. e. close to root) category,
1421             that one component logs more than it should,
1422              
1423             Here's how it works:
1424              
1425             ############################################################
1426             # Turn off logging in a lower-level category while keeping
1427             # it active in higher-level categories.
1428             ############################################################
1429             log4perl.rootLogger=DEBUG, LOGFILE
1430             log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE
1431              
1432             # ... Define appenders ...
1433              
1434             This way, log messages issued from within
1435             C<Deep::Down::The::Hierarchy> and below will be
1436             logged only if they're C<ERROR> or worse, while in all other system components
1437             even C<DEBUG> messages will be logged.
1438              
1439             =head2 Return Values
1440              
1441             All logging methods return values indicating if their message
1442             actually reached one or more appenders. If the message has been
1443             suppressed because of level constraints, C<undef> is returned.
1444              
1445             For example,
1446              
1447             my $ret = $logger->info("Message");
1448              
1449             will return C<undef> if the system debug level for the current category
1450             is not C<INFO> or more permissive.
1451             If Log::Log4perl
1452             forwarded the message to one or more appenders, the number of appenders
1453             is returned.
1454              
1455             If appenders decide to veto on the message with an appender threshold,
1456             the log method's return value will have them excluded. This means that if
1457             you've got one appender holding an appender threshold and you're
1458             logging a message
1459             which passes the system's log level hurdle but not the appender threshold,
1460             C<0> will be returned by the log function.
1461              
1462             The bottom line is: Logging functions will return a I<true> value if the message
1463             made it through to one or more appenders and a I<false> value if it didn't.
1464             This allows for constructs like
1465              
1466             $logger->fatal("@_") or print STDERR "@_\n";
1467              
1468             which will ensure that the fatal message isn't lost
1469             if the current level is lower than FATAL or printed twice if
1470             the level is acceptable but an appender already points to STDERR.
1471              
1472             =head2 Pitfalls with Categories
1473              
1474             Be careful with just blindly reusing the system's packages as
1475             categories. If you do, you'll get into trouble with inherited methods.
1476             Imagine the following class setup:
1477              
1478             use Log::Log4perl;
1479              
1480             ###########################################
1481             package Bar;
1482             ###########################################
1483             sub new {
1484             my($class) = @_;
1485             my $logger = Log::Log4perl::get_logger(__PACKAGE__);
1486             $logger->debug("Creating instance");
1487             bless {}, $class;
1488             }
1489             ###########################################
1490             package Bar::Twix;
1491             ###########################################
1492             our @ISA = qw(Bar);
1493              
1494             ###########################################
1495             package main;
1496             ###########################################
1497             Log::Log4perl->init(\ qq{
1498             log4perl.category.Bar.Twix = DEBUG, Screen
1499             log4perl.appender.Screen = Log::Log4perl::Appender::Screen
1500             log4perl.appender.Screen.layout = SimpleLayout
1501             });
1502              
1503             my $bar = Bar::Twix->new();
1504              
1505             C<Bar::Twix> just inherits everything from C<Bar>, including the constructor
1506             C<new()>.
1507             Contrary to what you might be thinking at first, this won't log anything.
1508             Reason for this is the C<get_logger()> call in package C<Bar>, which
1509             will always get a logger of the C<Bar> category, even if we call C<new()> via
1510             the C<Bar::Twix> package, which will make perl go up the inheritance
1511             tree to actually execute C<Bar::new()>. Since we've only defined logging
1512             behaviour for C<Bar::Twix> in the configuration file, nothing will happen.
1513              
1514             This can be fixed by changing the C<get_logger()> method in C<Bar::new()>
1515             to obtain a logger of the category matching the
1516             I<actual> class of the object, like in
1517              
1518             # ... in Bar::new() ...
1519             my $logger = Log::Log4perl::get_logger( $class );
1520              
1521             In a method other than the constructor, the class name of the actual
1522             object can be obtained by calling C<ref()> on the object reference, so
1523              
1524             package BaseClass;
1525             use Log::Log4perl qw( get_logger );
1526              
1527             sub new {
1528             bless {}, shift;
1529             }
1530              
1531             sub method {
1532             my( $self ) = @_;
1533              
1534             get_logger( ref $self )->debug( "message" );
1535             }
1536              
1537             package SubClass;
1538             our @ISA = qw(BaseClass);
1539              
1540             is the recommended pattern to make sure that
1541              
1542             my $sub = SubClass->new();
1543             $sub->meth();
1544              
1545             starts logging if the C<"SubClass"> category
1546             (and not the C<"BaseClass"> category has logging enabled at the DEBUG level.
1547              
1548             =head2 Initialize once and only once
1549              
1550             It's important to realize that Log::Log4perl gets initialized once and only
1551             once, typically at the start of a program or system. Calling C<init()>
1552             more than once will cause it to clobber the existing configuration and
1553             I<replace> it by the new one.
1554              
1555             If you're in a traditional CGI environment, where every request is
1556             handled by a new process, calling C<init()> every time is fine. In
1557             persistent environments like C<mod_perl>, however, Log::Log4perl
1558             should be initialized either at system startup time (Apache offers
1559             startup handlers for that) or via
1560              
1561             # Init or skip if already done
1562             Log::Log4perl->init_once($conf_file);
1563              
1564             C<init_once()> is identical to C<init()>, just with the exception
1565             that it will leave a potentially existing configuration alone and
1566             will only call C<init()> if Log::Log4perl hasn't been initialized yet.
1567              
1568             If you're just curious if Log::Log4perl has been initialized yet, the
1569             check
1570              
1571             if(Log::Log4perl->initialized()) {
1572             # Yes, Log::Log4perl has already been initialized
1573             } else {
1574             # No, not initialized yet ...
1575             }
1576              
1577             can be used.
1578              
1579             If you're afraid that the components of your system are stepping on
1580             each other's toes or if you are thinking that different components should
1581             initialize Log::Log4perl separately, try to consolidate your system
1582             to use a centralized Log4perl configuration file and use
1583             Log4perl's I<categories> to separate your components.
1584              
1585             =head2 Custom Filters
1586              
1587             Log4perl allows the use of customized filters in its appenders
1588             to control the output of messages. These filters might grep for
1589             certain text chunks in a message, verify that its priority
1590             matches or exceeds a certain level or that this is the 10th
1591             time the same message has been submitted -- and come to a log/no log
1592             decision based upon these circumstantial facts.
1593              
1594             Check out L<Log::Log4perl::Filter> for detailed instructions
1595             on how to use them.
1596              
1597             =head2 Performance
1598              
1599             The performance of Log::Log4perl calls obviously depends on a lot of things.
1600             But to give you a general idea, here's some rough numbers:
1601              
1602             On a Pentium 4 Linux box at 2.4 GHz, you'll get through
1603              
1604             =over 4
1605              
1606             =item *
1607              
1608             500,000 suppressed log statements per second
1609              
1610             =item *
1611              
1612             30,000 logged messages per second (using an in-memory appender)
1613              
1614             =item *
1615              
1616             init_and_watch delay mode: 300,000 suppressed, 30,000 logged.
1617             init_and_watch signal mode: 450,000 suppressed, 30,000 logged.
1618              
1619             =back
1620              
1621             Numbers depend on the complexity of the Log::Log4perl configuration.
1622             For a more detailed benchmark test, check the C<docs/benchmark.results.txt>
1623             document in the Log::Log4perl distribution.
1624              
1625             =head1 Cool Tricks
1626              
1627             Here's a collection of useful tricks for the advanced C<Log::Log4perl> user.
1628             For more, check the FAQ, either in the distribution
1629             (L<Log::Log4perl::FAQ>) or on L<http://log4perl.sourceforge.net>.
1630              
1631             =head2 Shortcuts
1632              
1633             When getting an instance of a logger, instead of saying
1634              
1635             use Log::Log4perl;
1636             my $logger = Log::Log4perl->get_logger();
1637              
1638             it's often more convenient to import the C<get_logger> method from
1639             C<Log::Log4perl> into the current namespace:
1640              
1641             use Log::Log4perl qw(get_logger);
1642             my $logger = get_logger();
1643              
1644             Please note this difference: To obtain the root logger, please use
1645             C<get_logger("")>, call it without parameters (C<get_logger()>), you'll
1646             get the logger of a category named after the current package.
1647             C<get_logger()> is equivalent to C<get_logger(__PACKAGE__)>.
1648              
1649             =head2 Alternative initialization
1650              
1651             Instead of having C<init()> read in a configuration file by specifying
1652             a file name or passing it a reference to an open filehandle
1653             (C<Log::Log4perl-E<gt>init( \*FILE )>),
1654             you can
1655             also pass in a reference to a string, containing the content of
1656             the file:
1657              
1658             Log::Log4perl->init( \$config_text );
1659              
1660             Also, if you've got the C<name=value> pairs of the configuration in
1661             a hash, you can just as well initialize C<Log::Log4perl> with
1662             a reference to it:
1663              
1664             my %key_value_pairs = (
1665             "log4perl.rootLogger" => "ERROR, LOGFILE",
1666             "log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File",
1667             ...
1668             );
1669              
1670             Log::Log4perl->init( \%key_value_pairs );
1671              
1672             Or also you can use a URL, see below:
1673              
1674             =head2 Using LWP to parse URLs
1675              
1676             (This section borrowed from XML::DOM::Parser by T.J. Mather).
1677              
1678             The init() function now also supports URLs, e.g. I<http://www.erols.com/enno/xsa.xml>.
1679             It uses LWP to download the file and then calls parse() on the resulting string.
1680             By default it will use a L<LWP::UserAgent> that is created as follows:
1681              
1682             use LWP::UserAgent;
1683             $LWP_USER_AGENT = LWP::UserAgent->new;
1684             $LWP_USER_AGENT->env_proxy;
1685              
1686             Note that env_proxy reads proxy settings from environment variables, which is what Log4perl needs to
1687             do to get through our firewall. If you want to use a different LWP::UserAgent, you can
1688             set it with
1689              
1690             Log::Log4perl::Config::set_LWP_UserAgent($my_agent);
1691              
1692             Currently, LWP is used when the filename (passed to parsefile) starts with one of
1693             the following URL schemes: http, https, ftp, wais, gopher, or file (followed by a colon.)
1694              
1695             Don't use this feature with init_and_watch().
1696              
1697             =head2 Automatic reloading of changed configuration files
1698              
1699             Instead of just statically initializing Log::Log4perl via
1700              
1701             Log::Log4perl->init($conf_file);
1702              
1703             there's a way to have Log::Log4perl periodically check for changes
1704             in the configuration and reload it if necessary:
1705              
1706             Log::Log4perl->init_and_watch($conf_file, $delay);
1707              
1708             In this mode, Log::Log4perl will examine the configuration file
1709             C<$conf_file> every C<$delay> seconds for changes via the file's
1710             last modification timestamp. If the file has been updated, it will
1711             be reloaded and replace the current Log::Log4perl configuration.
1712              
1713             The way this works is that with every logger function called
1714             (debug(), is_debug(), etc.), Log::Log4perl will check if the delay
1715             interval has expired. If so, it will run a -M file check on the
1716             configuration file. If its timestamp has been modified, the current
1717             configuration will be dumped and new content of the file will be
1718             loaded.
1719              
1720             This convenience comes at a price, though: Calling time() with every
1721             logging function call, especially the ones that are "suppressed" (!),
1722             will slow down these Log4perl calls by about 40%.
1723              
1724             To alleviate this performance hit a bit, C<init_and_watch()>
1725             can be configured to listen for a Unix signal to reload the
1726             configuration instead:
1727              
1728             Log::Log4perl->init_and_watch($conf_file, 'HUP');
1729              
1730             This will set up a signal handler for SIGHUP and reload the configuration
1731             if the application receives this signal, e.g. via the C<kill> command:
1732              
1733             kill -HUP pid
1734              
1735             where C<pid> is the process ID of the application. This will bring you back
1736             to about 85% of Log::Log4perl's normal execution speed for suppressed
1737             statements. For details, check out L<"Performance">. For more info
1738             on the signal handler, look for L<Log::Log4perl::Config::Watch/"SIGNAL MODE">.
1739              
1740             If you have a somewhat long delay set between physical config file checks
1741             or don't want to use the signal associated with the config file watcher,
1742             you can trigger a configuration reload at the next possible time by
1743             calling C<Log::Log4perl::Config-E<gt>watcher-E<gt>force_next_check()>.
1744              
1745             One thing to watch out for: If the configuration file contains a syntax
1746             or other fatal error, a running application will stop with C<die> if
1747             this damaged configuration will be loaded during runtime, triggered
1748             either by a signal or if the delay period expired and the change is
1749             detected. This behaviour might change in the future.
1750              
1751             To allow the application to intercept and control a configuration reload
1752             in init_and_watch mode, a callback can be specified:
1753              
1754             Log::Log4perl->init_and_watch($conf_file, 10, {
1755             preinit_callback => \&callback });
1756              
1757             If Log4perl determines that the configuration needs to be reloaded, it will
1758             call the C<preinit_callback> function without parameters. If the callback
1759             returns a true value, Log4perl will proceed and reload the configuration. If
1760             the callback returns a false value, Log4perl will keep the old configuration
1761             and skip reloading it until the next time around. Inside the callback, an
1762             application can run all kinds of checks, including accessing the configuration
1763             file, which is available via
1764             C<Log::Log4perl::Config-E<gt>watcher()-E<gt>file()>.
1765              
1766             =head2 Variable Substitution
1767              
1768             To avoid having to retype the same expressions over and over again,
1769             Log::Log4perl's configuration files support simple variable substitution.
1770             New variables are defined simply by adding
1771              
1772             varname = value
1773              
1774             lines to the configuration file before using
1775              
1776             ${varname}
1777              
1778             afterwards to recall the assigned values. Here's an example:
1779              
1780             layout_class = Log::Log4perl::Layout::PatternLayout
1781             layout_pattern = %d %F{1} %L> %m %n
1782            
1783             log4perl.category.Bar.Twix = WARN, Logfile, Screen
1784              
1785             log4perl.appender.Logfile = Log::Log4perl::Appender::File
1786             log4perl.appender.Logfile.filename = test.log
1787             log4perl.appender.Logfile.layout = ${layout_class}
1788             log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern}
1789              
1790             log4perl.appender.Screen = Log::Log4perl::Appender::Screen
1791             log4perl.appender.Screen.layout = ${layout_class}
1792             log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern}
1793              
1794             This is a convenient way to define two appenders with the same layout
1795             without having to retype the pattern definitions.
1796              
1797             Variable substitution via C<${varname}>
1798             will first try to find an explicitly defined
1799             variable. If that fails, it will check your shell's environment
1800             for a variable of that name. If that also fails, the program will C<die()>.
1801              
1802             =head2 Perl Hooks in the Configuration File
1803              
1804             If some of the values used in the Log4perl configuration file
1805             need to be dynamically modified by the program, use Perl hooks:
1806              
1807             log4perl.appender.File.filename = \
1808             sub { return getLogfileName(); }
1809              
1810             Each value starting with the string C<sub {...> is interpreted as Perl code to
1811             be executed at the time the application parses the configuration
1812             via C<Log::Log4perl::init()>. The return value of the subroutine
1813             is used by Log::Log4perl as the configuration value.
1814              
1815             The Perl code is executed in the C<main> package, functions in
1816             other packages have to be called in fully-qualified notation.
1817              
1818             Here's another example, utilizing an environment variable as a
1819             username for a DBI appender:
1820              
1821             log4perl.appender.DB.username = \
1822             sub { $ENV{DB_USER_NAME } }
1823              
1824             However, please note the difference between these code snippets and those
1825             used for user-defined conversion specifiers as discussed in
1826             L<Log::Log4perl::Layout::PatternLayout>:
1827             While the snippets above are run I<once>
1828             when C<Log::Log4perl::init()> is called, the conversion specifier
1829             snippets are executed I<each time> a message is rendered according to
1830             the PatternLayout.
1831              
1832             SECURITY NOTE: this feature means arbitrary perl code can be embedded in the
1833             config file. In the rare case where the people who have access to your config
1834             file are different from the people who write your code and shouldn't have
1835             execute rights, you might want to set
1836              
1837             Log::Log4perl::Config->allow_code(0);
1838              
1839             before you call init(). Alternatively you can supply a restricted set of
1840             Perl opcodes that can be embedded in the config file as described in
1841             L<"Restricting what Opcodes can be in a Perl Hook">.
1842              
1843             =head2 Restricting what Opcodes can be in a Perl Hook
1844              
1845             The value you pass to Log::Log4perl::Config->allow_code() determines whether
1846             the code that is embedded in the config file is eval'd unrestricted, or
1847             eval'd in a Safe compartment. By default, a value of '1' is assumed,
1848             which does a normal 'eval' without any restrictions. A value of '0'
1849             however prevents any embedded code from being evaluated.
1850              
1851             If you would like fine-grained control over what can and cannot be included
1852             in embedded code, then please utilize the following methods:
1853              
1854             Log::Log4perl::Config->allow_code( $allow );
1855             Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... );
1856             Log::Log4perl::Config->vars_shared_with_safe_compartment( [ \%vars | $package, \@vars ] );
1857             Log::Log4perl::Config->allowed_code_ops_convenience_map( [ \%map | $name, \@mask ] );
1858              
1859             Log::Log4perl::Config-E<gt>allowed_code_ops() takes a list of opcode masks
1860             that are allowed to run in the compartment. The opcode masks must be
1861             specified as described in L<Opcode>:
1862              
1863             Log::Log4perl::Config->allowed_code_ops(':subprocess');
1864              
1865             This example would allow Perl operations like backticks, system, fork, and
1866             waitpid to be executed in the compartment. Of course, you probably don't
1867             want to use this mask -- it would allow exactly what the Safe compartment is
1868             designed to prevent.
1869              
1870             Log::Log4perl::Config-E<gt>vars_shared_with_safe_compartment()
1871             takes the symbols which
1872             should be exported into the Safe compartment before the code is evaluated.
1873             The keys of this hash are the package names that the symbols are in, and the
1874             values are array references to the literal symbol names. For convenience,
1875             the default settings export the '%ENV' hash from the 'main' package into the
1876             compartment:
1877              
1878             Log::Log4perl::Config->vars_shared_with_safe_compartment(
1879             main => [ '%ENV' ],
1880             );
1881              
1882             Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map() is an accessor
1883             method to a map of convenience names to opcode masks. At present, the
1884             following convenience names are defined:
1885              
1886             safe = [ ':browse' ]
1887             restrictive = [ ':default' ]
1888              
1889             For convenience, if Log::Log4perl::Config-E<gt>allow_code() is called with a
1890             value which is a key of the map previously defined with
1891             Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map(), then the
1892             allowed opcodes are set according to the value defined in the map. If this
1893             is confusing, consider the following:
1894              
1895             use Log::Log4perl;
1896            
1897             my $config = <<'END';
1898             log4perl.logger = INFO, Main
1899             log4perl.appender.Main = Log::Log4perl::Appender::File
1900             log4perl.appender.Main.filename = \
1901             sub { "example" . getpwuid($<) . ".log" }
1902             log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout
1903             END
1904            
1905             $Log::Log4perl::Config->allow_code('restrictive');
1906             Log::Log4perl->init( \$config ); # will fail
1907             $Log::Log4perl::Config->allow_code('safe');
1908             Log::Log4perl->init( \$config ); # will succeed
1909              
1910             The reason that the first call to -E<gt>init() fails is because the
1911             'restrictive' name maps to an opcode mask of ':default'. getpwuid() is not
1912             part of ':default', so -E<gt>init() fails. The 'safe' name maps to an opcode
1913             mask of ':browse', which allows getpwuid() to run, so -E<gt>init() succeeds.
1914              
1915             allowed_code_ops_convenience_map() can be invoked in several ways:
1916              
1917             =over 4
1918              
1919             =item allowed_code_ops_convenience_map()
1920              
1921             Returns the entire convenience name map as a hash reference in scalar
1922             context or a hash in list context.
1923              
1924             =item allowed_code_ops_convenience_map( \%map )
1925              
1926             Replaces the entire convenience name map with the supplied hash reference.
1927              
1928             =item allowed_code_ops_convenience_map( $name )
1929              
1930             Returns the opcode mask for the given convenience name, or undef if no such
1931             name is defined in the map.
1932              
1933             =item allowed_code_ops_convenience_map( $name, \@mask )
1934              
1935             Adds the given name/mask pair to the convenience name map. If the name
1936             already exists in the map, it's value is replaced with the new mask.
1937              
1938             =back
1939              
1940             as can vars_shared_with_safe_compartment():
1941              
1942             =over 4
1943              
1944             =item vars_shared_with_safe_compartment()
1945              
1946             Return the entire map of packages to variables as a hash reference in scalar
1947             context or a hash in list context.
1948              
1949             =item vars_shared_with_safe_compartment( \%packages )
1950              
1951             Replaces the entire map of packages to variables with the supplied hash
1952             reference.
1953              
1954             =item vars_shared_with_safe_compartment( $package )
1955              
1956             Returns the arrayref of variables to be shared for a specific package.
1957              
1958             =item vars_shared_with_safe_compartment( $package, \@vars )
1959              
1960             Adds the given package / varlist pair to the map. If the package already
1961             exists in the map, it's value is replaced with the new arrayref of variable
1962             names.
1963              
1964             =back
1965              
1966             For more information on opcodes and Safe Compartments, see L<Opcode> and
1967             L<Safe>.
1968              
1969             =head2 Changing the Log Level on a Logger
1970              
1971             Log4perl provides some internal functions for quickly adjusting the
1972             log level from within a running Perl program.
1973              
1974             Now, some people might
1975             argue that you should adjust your levels from within an external
1976             Log4perl configuration file, but Log4perl is everybody's darling.
1977              
1978             Typically run-time adjusting of levels is done
1979             at the beginning, or in response to some external input (like a
1980             "more logging" runtime command for diagnostics).
1981              
1982             You get the log level from a logger object with:
1983              
1984             $current_level = $logger->level();
1985              
1986             and you may set it with the same method, provided you first
1987             imported the log level constants, with:
1988              
1989             use Log::Log4perl::Level;
1990              
1991             Then you can set the level on a logger to one of the constants,
1992              
1993             $logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL
1994              
1995             To B<increase> the level of logging currently being done, use:
1996              
1997             $logger->more_logging($delta);
1998              
1999             and to B<decrease> it, use:
2000              
2001             $logger->less_logging($delta);
2002              
2003             $delta must be a positive integer (for now, we may fix this later ;).
2004              
2005             There are also two equivalent functions:
2006              
2007             $logger->inc_level($delta);
2008             $logger->dec_level($delta);
2009              
2010             They're included to allow you a choice in readability. Some folks
2011             will prefer more/less_logging, as they're fairly clear in what they
2012             do, and allow the programmer not to worry too much about what a Level
2013             is and whether a higher level means more or less logging. However,
2014             other folks who do understand and have lots of code that deals with
2015             levels will probably prefer the inc_level() and dec_level() methods as
2016             they want to work with Levels and not worry about whether that means
2017             more or less logging. :)
2018              
2019             That diatribe aside, typically you'll use more_logging() or inc_level()
2020             as such:
2021              
2022             my $v = 0; # default level of verbosity.
2023            
2024             GetOptions("v+" => \$v, ...);
2025              
2026             if( $v ) {
2027             $logger->more_logging($v); # inc logging level once for each -v in ARGV
2028             }
2029              
2030             =head2 Custom Log Levels
2031              
2032             First off, let me tell you that creating custom levels is heavily
2033             deprecated by the log4j folks. Indeed, instead of creating additional
2034             levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL,
2035             you should use categories to control the amount of logging smartly,
2036             based on the location of the log-active code in the system.
2037              
2038             Nevertheless,
2039             Log4perl provides a nice way to create custom levels via the
2040             create_custom_level() routine function. However, this must be done
2041             before the first call to init() or get_logger(). Say you want to create
2042             a NOTIFY logging level that comes after WARN (and thus before INFO).
2043             You'd do such as follows:
2044              
2045             use Log::Log4perl;
2046             use Log::Log4perl::Level;
2047              
2048             Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN");
2049              
2050             And that's it! C<create_custom_level()> creates the following functions /
2051             variables for level FOO:
2052              
2053             $FOO_INT # integer to use in L4p::Level::to_level()
2054             $logger->foo() # log function to log if level = FOO
2055             $logger->is_foo() # true if current level is >= FOO
2056              
2057             These levels can also be used in your
2058             config file, but note that your config file probably won't be
2059             portable to another log4perl or log4j environment unless you've
2060             made the appropriate mods there too.
2061              
2062             Since Log4perl translates log levels to syslog and Log::Dispatch if
2063             their appenders are used, you may add mappings for custom levels as well:
2064              
2065             Log::Log4perl::Level::add_priority("NOTIFY", "WARN",
2066             $syslog_equiv, $log_dispatch_level);
2067              
2068             For example, if your new custom "NOTIFY" level is supposed to map
2069             to syslog level 2 ("LOG_NOTICE") and Log::Dispatch level 2 ("notice"), use:
2070              
2071             Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN", 2, 2);
2072              
2073             =head2 System-wide log levels
2074              
2075             As a fairly drastic measure to decrease (or increase) the logging level
2076             all over the system with one single configuration option, use the C<threshold>
2077             keyword in the Log4perl configuration file:
2078              
2079             log4perl.threshold = ERROR
2080              
2081             sets the system-wide (or hierarchy-wide according to the log4j documentation)
2082             to ERROR and therefore deprives every logger in the system of the right
2083             to log lower-prio messages.
2084              
2085             =head2 Easy Mode
2086              
2087             For teaching purposes (especially for [1]), I've put C<:easy> mode into
2088             C<Log::Log4perl>, which just initializes a single root logger with a
2089             defined priority and a screen appender including some nice standard layout:
2090              
2091             ### Initialization Section
2092             use Log::Log4perl qw(:easy);
2093             Log::Log4perl->easy_init($ERROR); # Set priority of root logger to ERROR
2094              
2095             ### Application Section
2096             my $logger = get_logger();
2097             $logger->fatal("This will get logged.");
2098             $logger->debug("This won't.");
2099              
2100             This will dump something like
2101              
2102             2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.
2103              
2104             to the screen. While this has been proven to work well familiarizing people
2105             with C<Log::Logperl> slowly, effectively avoiding to clobber them over the
2106             head with a
2107             plethora of different knobs to fiddle with (categories, appenders, levels,
2108             layout), the overall mission of C<Log::Log4perl> is to let people use
2109             categories right from the start to get used to the concept. So, let's keep
2110             this one fairly hidden in the man page (congrats on reading this far :).
2111              
2112             =head2 Stealth loggers
2113              
2114             Sometimes, people are lazy. If you're whipping up a 50-line script and want
2115             the comfort of Log::Log4perl without having the burden of carrying a
2116             separate log4perl.conf file or a 5-liner defining that you want to append
2117             your log statements to a file, you can use the following features:
2118              
2119             use Log::Log4perl qw(:easy);
2120              
2121             Log::Log4perl->easy_init( { level => $DEBUG,
2122             file => ">>test.log" } );
2123              
2124             # Logs to test.log via stealth logger
2125             DEBUG("Debug this!");
2126             INFO("Info this!");
2127             WARN("Warn this!");
2128             ERROR("Error this!");
2129              
2130             some_function();
2131              
2132             sub some_function {
2133             # Same here
2134             FATAL("Fatal this!");
2135             }
2136              
2137             In C<:easy> mode, C<Log::Log4perl> will instantiate a I<stealth logger>
2138             and introduce the
2139             convenience functions C<TRACE>, C<DEBUG()>, C<INFO()>, C<WARN()>,
2140             C<ERROR()>, C<FATAL()>, and C<ALWAYS> into the package namespace.
2141             These functions simply take messages as
2142             arguments and forward them to the stealth loggers methods (C<debug()>,
2143             C<info()>, and so on).
2144              
2145             If a message should never be blocked, regardless of the log level,
2146             use the C<ALWAYS> function which corresponds to a log level of C<OFF>:
2147              
2148             ALWAYS "This will be printed regardless of the log level";
2149              
2150             The C<easy_init> method can be called with a single level value to
2151             create a STDERR appender and a root logger as in
2152              
2153             Log::Log4perl->easy_init($DEBUG);
2154              
2155             or, as shown below (and in the example above)
2156             with a reference to a hash, specifying values
2157             for C<level> (the logger's priority), C<file> (the appender's data sink),
2158             C<category> (the logger's category and C<layout> for the appender's
2159             pattern layout specification.
2160             All key-value pairs are optional, they
2161             default to C<$DEBUG> for C<level>, C<STDERR> for C<file>,
2162             C<""> (root category) for C<category> and
2163             C<%d %m%n> for C<layout>:
2164              
2165             Log::Log4perl->easy_init( { level => $DEBUG,
2166             file => ">test.log",
2167             utf8 => 1,
2168             category => "Bar::Twix",
2169             layout => '%F{1}-%L-%M: %m%n' } );
2170              
2171             The C<file> parameter takes file names preceded by C<"E<gt>">
2172             (overwrite) and C<"E<gt>E<gt>"> (append) as arguments. This will
2173             cause C<Log::Log4perl::Appender::File> appenders to be created behind
2174             the scenes. Also the keywords C<STDOUT> and C<STDERR> (no C<E<gt>> or
2175             C<E<gt>E<gt>>) are recognized, which will utilize and configure
2176             C<Log::Log4perl::Appender::Screen> appropriately. The C<utf8> flag,
2177             if set to a true value, runs a C<binmode> command on the file handle
2178             to establish a utf8 line discipline on the file, otherwise you'll get a
2179             'wide character in print' warning message and probably not what you'd
2180             expect as output.
2181              
2182             The stealth loggers can be used in different packages, you just need to make
2183             sure you're calling the "use" function in every package you're using
2184             C<Log::Log4perl>'s easy services:
2185              
2186             package Bar::Twix;
2187             use Log::Log4perl qw(:easy);
2188             sub eat { DEBUG("Twix mjam"); }
2189              
2190             package Bar::Mars;
2191             use Log::Log4perl qw(:easy);
2192             sub eat { INFO("Mars mjam"); }
2193              
2194             package main;
2195              
2196             use Log::Log4perl qw(:easy);
2197              
2198             Log::Log4perl->easy_init( { level => $DEBUG,
2199             file => ">>test.log",
2200             category => "Bar::Twix",
2201             layout => '%F{1}-%L-%M: %m%n' },
2202             { level => $DEBUG,
2203             file => "STDOUT",
2204             category => "Bar::Mars",
2205             layout => '%m%n' },
2206             );
2207             Bar::Twix::eat();
2208             Bar::Mars::eat();
2209              
2210             As shown above, C<easy_init()> will take any number of different logger
2211             definitions as hash references.
2212              
2213             Also, stealth loggers feature the functions C<LOGWARN()>, C<LOGDIE()>,
2214             and C<LOGEXIT()>,
2215             combining a logging request with a subsequent Perl warn() or die() or exit()
2216             statement. So, for example
2217              
2218             if($all_is_lost) {
2219             LOGDIE("Terrible Problem");
2220             }
2221              
2222             will log the message if the package's logger is at least C<FATAL> but
2223             C<die()> (including the traditional output to STDERR) in any case afterwards.
2224              
2225             See L<"Log and die or warn"> for the similar C<logdie()> and C<logwarn()>
2226             functions of regular (i.e non-stealth) loggers.
2227              
2228             Similarily, C<LOGCARP()>, C<LOGCLUCK()>, C<LOGCROAK()>, and C<LOGCONFESS()>
2229             are provided in C<:easy> mode, facilitating the use of C<logcarp()>,
2230             C<logcluck()>, C<logcroak()>, and C<logconfess()> with stealth loggers.
2231              
2232             B<When using Log::Log4perl in easy mode,
2233             please make sure you understand the implications of
2234             L</"Pitfalls with Categories">>.
2235              
2236             By the way, these convenience functions perform exactly as fast as the
2237             standard Log::Log4perl logger methods, there's I<no> performance penalty
2238             whatsoever.
2239              
2240             =head2 Nested Diagnostic Context (NDC)
2241              
2242             If you find that your application could use a global (thread-specific)
2243             data stack which your loggers throughout the system have easy access to,
2244             use Nested Diagnostic Contexts (NDCs). Also check out
2245             L<"Mapped Diagnostic Context (MDC)">, this might turn out to be even more
2246             useful.
2247              
2248             For example, when handling a request of a web client, it's probably
2249             useful to have the user's IP address available in all log statements
2250             within code dealing with this particular request. Instead of passing
2251             this piece of data around between your application functions, you can just
2252             use the global (but thread-specific) NDC mechanism. It allows you
2253             to push data pieces (scalars usually) onto its stack via
2254              
2255             Log::Log4perl::NDC->push("San");
2256             Log::Log4perl::NDC->push("Francisco");
2257              
2258             and have your loggers retrieve them again via the "%x" placeholder in
2259             the PatternLayout. With the stack values above and a PatternLayout format
2260             like "%x %m%n", the call
2261              
2262             $logger->debug("rocks");
2263              
2264             will end up as
2265              
2266             San Francisco rocks
2267              
2268             in the log appender.
2269              
2270             The stack mechanism allows for nested structures.
2271             Just make sure that at the end of the request, you either decrease the stack
2272             one by one by calling
2273              
2274             Log::Log4perl::NDC->pop();
2275             Log::Log4perl::NDC->pop();
2276              
2277             or clear out the entire NDC stack by calling
2278              
2279             Log::Log4perl::NDC->remove();
2280              
2281             Even if you should forget to do that, C<Log::Log4perl> won't grow the stack
2282             indefinitely, but limit it to a maximum, defined in C<Log::Log4perl::NDC>
2283             (currently 5). A call to C<push()> on a full stack will just replace
2284             the topmost element by the new value.
2285              
2286             Again, the stack is always available via the "%x" placeholder
2287             in the Log::Log4perl::Layout::PatternLayout class whenever a logger
2288             fires. It will replace "%x" by the blank-separated list of the
2289             values on the stack. It does that by just calling
2290              
2291             Log::Log4perl::NDC->get();
2292              
2293             internally. See details on how this standard log4j feature is implemented
2294             in L<Log::Log4perl::NDC>.
2295              
2296             =head2 Mapped Diagnostic Context (MDC)
2297              
2298             Just like the previously discussed NDC stores thread-specific
2299             information in a stack structure, the MDC implements a hash table
2300             to store key/value pairs in.
2301              
2302             The static method
2303              
2304             Log::Log4perl::MDC->put($key, $value);
2305              
2306             stores C<$value> under a key C<$key>, with which it can be retrieved later
2307             (possibly in a totally different part of the system) by calling
2308             the C<get> method:
2309              
2310             my $value = Log::Log4perl::MDC->get($key);
2311              
2312             If no value has been stored previously under C<$key>, the C<get> method
2313             will return C<undef>.
2314              
2315             Typically, MDC values are retrieved later on via the C<"%X{...}"> placeholder
2316             in C<Log::Log4perl::Layout::PatternLayout>. If the C<get()> method
2317             returns C<undef>, the placeholder will expand to the string C<[undef]>.
2318              
2319             An application taking a web request might store the remote host
2320             like
2321              
2322             Log::Log4perl::MDC->put("remote_host", $r->headers("HOST"));
2323              
2324             at its beginning and if the appender's layout looks something like
2325              
2326             log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n
2327              
2328             then a log statement like
2329              
2330             DEBUG("Content delivered");
2331              
2332             will log something like
2333              
2334             adsl-63.dsl.snf.pacbell.net: Content delivered
2335              
2336             later on in the program.
2337              
2338             For details, please check L<Log::Log4perl::MDC>.
2339              
2340             =head2 Resurrecting hidden Log4perl Statements
2341              
2342             Sometimes scripts need to be deployed in environments without having
2343             Log::Log4perl installed yet. On the other hand, you don't want to
2344             live without your Log4perl statements -- they're gonna come in
2345             handy later.
2346              
2347             So, just deploy your script with Log4perl statements commented out with the
2348             pattern C<###l4p>, like in
2349              
2350             ###l4p DEBUG "It works!";
2351             # ...
2352             ###l4p INFO "Really!";
2353              
2354             If Log::Log4perl is available,
2355             use the C<:resurrect> tag to have Log4perl resurrect those buried
2356             statements before the script starts running:
2357              
2358             use Log::Log4perl qw(:resurrect :easy);
2359              
2360             ###l4p Log::Log4perl->easy_init($DEBUG);
2361             ###l4p DEBUG "It works!";
2362             # ...
2363             ###l4p INFO "Really!";
2364              
2365             This will have a source filter kick in and indeed print
2366              
2367             2004/11/18 22:08:46 It works!
2368             2004/11/18 22:08:46 Really!
2369              
2370             In environments lacking Log::Log4perl, just comment out the first line
2371             and the script will run nevertheless (but of course without logging):
2372              
2373             # use Log::Log4perl qw(:resurrect :easy);
2374              
2375             ###l4p Log::Log4perl->easy_init($DEBUG);
2376             ###l4p DEBUG "It works!";
2377             # ...
2378             ###l4p INFO "Really!";
2379              
2380             because everything's a regular comment now. Alternatively, put the
2381             magic Log::Log4perl comment resurrection line into your shell's
2382             PERL5OPT environment variable, e.g. for bash:
2383              
2384             set PERL5OPT=-MLog::Log4perl=:resurrect,:easy
2385             export PERL5OPT
2386              
2387             This will awaken the giant within an otherwise silent script like
2388             the following:
2389              
2390             #!/usr/bin/perl
2391              
2392             ###l4p Log::Log4perl->easy_init($DEBUG);
2393             ###l4p DEBUG "It works!";
2394              
2395             As of C<Log::Log4perl> 1.12, you can even force I<all> modules
2396             loaded by a script to have their hidden Log4perl statements
2397             resurrected. For this to happen, load C<Log::Log4perl::Resurrector>
2398             I<before> loading any modules:
2399              
2400             use Log::Log4perl qw(:easy);
2401             use Log::Log4perl::Resurrector;
2402              
2403             use Foobar; # All hidden Log4perl statements in here will
2404             # be uncommented before Foobar gets loaded.
2405              
2406             Log::Log4perl->easy_init($DEBUG);
2407             ...
2408              
2409             Check the C<Log::Log4perl::Resurrector> manpage for more details.
2410              
2411             =head2 Access defined appenders
2412              
2413             All appenders defined in the configuration file or via Perl code
2414             can be retrieved by the C<appender_by_name()> class method. This comes
2415             in handy if you want to manipulate or query appender properties after
2416             the Log4perl configuration has been loaded via C<init()>.
2417              
2418             Note that internally, Log::Log4perl uses the C<Log::Log4perl::Appender>
2419             wrapper class to control the real appenders (like
2420             C<Log::Log4perl::Appender::File> or C<Log::Dispatch::FileRotate>).
2421             The C<Log::Log4perl::Appender> class has an C<appender> attribute,
2422             pointing to the real appender.
2423              
2424             The reason for this is that external appenders like
2425             C<Log::Dispatch::FileRotate> don't support all of Log::Log4perl's
2426             appender control mechanisms (like appender thresholds).
2427              
2428             The previously mentioned method C<appender_by_name()> returns a
2429             reference to the I<real> appender object. If you want access to the
2430             wrapper class (e.g. if you want to modify the appender's threshold),
2431             use the hash C<$Log::Log4perl::Logger::APPENDER_BY_NAME{...}> instead,
2432             which holds references to all appender wrapper objects.
2433              
2434             =head2 Modify appender thresholds
2435              
2436             To set an appender's threshold, use its C<threshold()> method:
2437              
2438             $app->threshold( $FATAL );
2439              
2440             To conveniently adjust I<all> appender thresholds (e.g. because a script
2441             uses more_logging()), use
2442              
2443             # decrease thresholds of all appenders
2444             Log::Log4perl->appender_thresholds_adjust(-1);
2445              
2446             This will decrease the thresholds of all appenders in the system by
2447             one level, i.e. WARN becomes INFO, INFO becomes DEBUG, etc. To only modify
2448             selected ones, use
2449              
2450             # decrease thresholds of selected appenders
2451             Log::Log4perl->appender_thresholds_adjust(-1, ['AppName1', ...]);
2452              
2453             and pass the names of affected appenders in a ref to an array.
2454              
2455             =head1 Advanced configuration within Perl
2456              
2457             Initializing Log::Log4perl can certainly also be done from within Perl.
2458             At last, this is what C<Log::Log4perl::Config> does behind the scenes.
2459             Log::Log4perl's configuration file parsers are using a publically
2460             available API to set up Log::Log4perl's categories, appenders and layouts.
2461              
2462             Here's an example on how to configure two appenders with the same layout
2463             in Perl, without using a configuration file at all:
2464              
2465             ########################
2466             # Initialization section
2467             ########################
2468             use Log::Log4perl;
2469             use Log::Log4perl::Layout;
2470             use Log::Log4perl::Level;
2471              
2472             # Define a category logger
2473             my $log = Log::Log4perl->get_logger("Foo::Bar");
2474              
2475             # Define a layout
2476             my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
2477              
2478             # Define a file appender
2479             my $file_appender = Log::Log4perl::Appender->new(
2480             "Log::Log4perl::Appender::File",
2481             name => "filelog",
2482             filename => "/tmp/my.log");
2483              
2484             # Define a stdout appender
2485             my $stdout_appender = Log::Log4perl::Appender->new(
2486             "Log::Log4perl::Appender::Screen",
2487             name => "screenlog",
2488             stderr => 0);
2489              
2490             # Define a mixed stderr/stdout appender
2491             my $mixed_stdout_stderr_appender = Log::Log4perl::Appender->new(
2492             "Log::Log4perl::Appender::Screen",
2493             name => "screenlog",
2494             stderr => { ERROR => 1, FATAL => 1 });
2495              
2496             # Have both appenders use the same layout (could be different)
2497             $stdout_appender->layout($layout);
2498             $file_appender->layout($layout);
2499              
2500             $log->add_appender($stdout_appender);
2501             $log->add_appender($file_appender);
2502             $log->level($INFO);
2503              
2504             Please note the class of the appender object is passed as a I<string> to
2505             C<Log::Log4perl::Appender> in the I<first> argument. Behind the scenes,
2506             C<Log::Log4perl::Appender> will create the necessary
2507             C<Log::Log4perl::Appender::*> (or C<Log::Dispatch::*>) object and pass
2508             along the name value pairs we provided to
2509             C<Log::Log4perl::Appender-E<gt>new()> after the first argument.
2510              
2511             The C<name> value is optional and if you don't provide one,
2512             C<Log::Log4perl::Appender-E<gt>new()> will create a unique one for you.
2513             The names and values of additional parameters are dependent on the requirements
2514             of the particular appender class and can be looked up in their
2515             manual pages.
2516              
2517             A side note: In case you're wondering if
2518             C<Log::Log4perl::Appender-E<gt>new()> will also take care of the
2519             C<min_level> argument to the C<Log::Dispatch::*> constructors called
2520             behind the scenes -- yes, it does. This is because we want the
2521             C<Log::Dispatch> objects to blindly log everything we send them
2522             (C<debug> is their lowest setting) because I<we> in C<Log::Log4perl>
2523             want to call the shots and decide on when and what to log.
2524              
2525             The call to the appender's I<layout()> method specifies the format (as a
2526             previously created C<Log::Log4perl::Layout::PatternLayout> object) in which the
2527             message is being logged in the specified appender.
2528             If you don't specify a layout, the logger will fall back to
2529             C<Log::Log4perl::SimpleLayout>, which logs the debug level, a hyphen (-)
2530             and the log message.
2531              
2532             Layouts are objects, here's how you create them:
2533              
2534             # Create a simple layout
2535             my $simple = Log::Log4perl::SimpleLayout();
2536              
2537             # create a flexible layout:
2538             # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\n")
2539             my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n");
2540              
2541             Every appender has exactly one layout assigned to it. You assign
2542             the layout to the appender using the appender's C<layout()> object:
2543              
2544             my $app = Log::Log4perl::Appender->new(
2545             "Log::Log4perl::Appender::Screen",
2546             name => "screenlog",
2547             stderr => 0);
2548              
2549             # Assign the previously defined flexible layout
2550             $app->layout($pattern);
2551              
2552             # Add the appender to a previously defined logger
2553             $logger->add_appender($app);
2554              
2555             # ... and you're good to go!
2556             $logger->debug("Blah");
2557             # => "2002/07/10 23:55:35 (test.pl:207)> Blah\n"
2558              
2559             It's also possible to remove appenders from a logger:
2560              
2561             $logger->remove_appender($appender_name);
2562              
2563             will remove an appender, specified by name, from a given logger.
2564             Please note that this does
2565             I<not> remove an appender from the system.
2566              
2567             To eradicate an appender from the system,
2568             you need to call C<Log::Log4perl-E<gt>eradicate_appender($appender_name)>
2569             which will first remove the appender from every logger in the system
2570             and then will delete all references Log4perl holds to it.
2571              
2572             To remove a logger from the system, use
2573             C<Log::Log4perl-E<gt>remove_logger($logger)>. After the remaining
2574             reference C<$logger> goes away, the logger will self-destruct. If the
2575             logger in question is a stealth logger, all of its convenience shortcuts
2576             (DEBUG, INFO, etc) will turn into no-ops.
2577              
2578             =head1 How about Log::Dispatch::Config?
2579              
2580             Tatsuhiko Miyagawa's C<Log::Dispatch::Config> is a very clever
2581             simplified logger implementation, covering some of the I<log4j>
2582             functionality. Among the things that
2583             C<Log::Log4perl> can but C<Log::Dispatch::Config> can't are:
2584              
2585             =over 4
2586              
2587             =item *
2588              
2589             You can't assign categories to loggers. For small systems that's fine,
2590             but if you can't turn off and on detailed logging in only a tiny
2591             subsystem of your environment, you're missing out on a majorly
2592             useful log4j feature.
2593              
2594             =item *
2595              
2596             Defining appender thresholds. Important if you want to solve problems like
2597             "log all messages of level FATAL to STDERR, plus log all DEBUG
2598             messages in C<Foo::Bar> to a log file". If you don't have appenders
2599             thresholds, there's no way to prevent cluttering STDERR with DEBUG messages.
2600              
2601             =item *
2602              
2603             PatternLayout specifications in accordance with the standard
2604             (e.g. "%d{HH:mm}").
2605              
2606             =back
2607              
2608             Bottom line: Log::Dispatch::Config is fine for small systems with
2609             simple logging requirements. However, if you're
2610             designing a system with lots of subsystems which you need to control
2611             independently, you'll love the features of C<Log::Log4perl>,
2612             which is equally easy to use.
2613              
2614             =head1 Using Log::Log4perl with wrapper functions and classes
2615              
2616             If you don't use C<Log::Log4perl> as described above,
2617             but from a wrapper function, the pattern layout will generate wrong data
2618             for %F, %C, %L, and the like. Reason for this is that C<Log::Log4perl>'s
2619             loggers assume a static caller depth to the application that's using them.
2620              
2621             If you're using
2622             one (or more) wrapper functions, C<Log::Log4perl> will indicate where
2623             your logger function called the loggers, not where your application
2624             called your wrapper:
2625              
2626             use Log::Log4perl qw(:easy);
2627             Log::Log4perl->easy_init({ level => $DEBUG,
2628             layout => "%M %m%n" });
2629              
2630             sub mylog {
2631             my($message) = @_;
2632              
2633             DEBUG $message;
2634             }
2635              
2636             sub func {
2637             mylog "Hello";
2638             }
2639              
2640             func();
2641              
2642             prints
2643              
2644             main::mylog Hello
2645              
2646             but that's probably not what your application expects. Rather, you'd
2647             want
2648              
2649             main::func Hello
2650              
2651             because the C<func> function called your logging function.
2652              
2653             But don't despair, there's a solution: Just register your wrapper
2654             package with Log4perl beforehand. If Log4perl then finds that it's being
2655             called from a registered wrapper, it will automatically step up to the
2656             next call frame.
2657              
2658             Log::Log4perl->wrapper_register(__PACKAGE__);
2659              
2660             sub mylog {
2661             my($message) = @_;
2662              
2663             DEBUG $message;
2664             }
2665              
2666             Alternatively, you can increase the value of the global variable
2667             C<$Log::Log4perl::caller_depth> (defaults to 0) by one for every
2668             wrapper that's in between your application and C<Log::Log4perl>,
2669             then C<Log::Log4perl> will compensate for the difference:
2670              
2671             sub mylog {
2672             my($message) = @_;
2673              
2674             local $Log::Log4perl::caller_depth =
2675             $Log::Log4perl::caller_depth + 1;
2676             DEBUG $message;
2677             }
2678              
2679             Also, note that if you're writing a subclass of Log4perl, like
2680              
2681             package MyL4pWrapper;
2682             use Log::Log4perl;
2683             our @ISA = qw(Log::Log4perl);
2684              
2685             and you want to call get_logger() in your code, like
2686              
2687             use MyL4pWrapper;
2688              
2689             sub get_logger {
2690             my $logger = Log::Log4perl->get_logger();
2691             }
2692              
2693             then the get_logger() call will get a logger for the C<MyL4pWrapper>
2694             category, not for the package calling the wrapper class as in
2695              
2696             package UserPackage;
2697             my $logger = MyL4pWrapper->get_logger();
2698              
2699             To have the above call to get_logger return a logger for the
2700             "UserPackage" category, you need to tell Log4perl that "MyL4pWrapper"
2701             is a Log4perl wrapper class:
2702              
2703             use MyL4pWrapper;
2704             Log::Log4perl->wrapper_register(__PACKAGE__);
2705              
2706             sub get_logger {
2707             # Now gets a logger for the category of the calling package
2708             my $logger = Log::Log4perl->get_logger();
2709             }
2710              
2711             This feature works both for Log4perl-relaying classes like the wrapper
2712             described above, and for wrappers that inherit from Log4perl use Log4perl's
2713             get_logger function via inheritance, alike.
2714              
2715             =head1 Access to Internals
2716              
2717             The following methods are only of use if you want to peek/poke in
2718             the internals of Log::Log4perl. Be careful not to disrupt its
2719             inner workings.
2720              
2721             =over 4
2722              
2723             =item C<< Log::Log4perl->appenders() >>
2724              
2725             To find out which appenders are currently defined (not only
2726             for a particular logger, but overall), a C<appenders()>
2727             method is available to return a reference to a hash mapping appender
2728             names to their Log::Log4perl::Appender object references.
2729              
2730             =back
2731              
2732             =head1 Dirty Tricks
2733              
2734             =over 4
2735              
2736             =item infiltrate_lwp()
2737              
2738             The famous LWP::UserAgent module isn't Log::Log4perl-enabled. Often, though,
2739             especially when tracing Web-related problems, it would be helpful to get
2740             some insight on what's happening inside LWP::UserAgent. Ideally, LWP::UserAgent
2741             would even play along in the Log::Log4perl framework.
2742              
2743             A call to C<Log::Log4perl-E<gt>infiltrate_lwp()> does exactly this.
2744             In a very rude way, it pulls the rug from under LWP::UserAgent and transforms
2745             its C<debug/conn> messages into C<debug()> calls of loggers of the category
2746             C<"LWP::UserAgent">. Similarily, C<LWP::UserAgent>'s C<trace> messages
2747             are turned into C<Log::Log4perl>'s C<info()> method calls. Note that this
2748             only works for LWP::UserAgent versions E<lt> 5.822, because this (and
2749             probably later) versions miss debugging functions entirely.
2750              
2751             =item Suppressing 'duplicate' LOGDIE messages
2752              
2753             If a script with a simple Log4perl configuration uses logdie() to catch
2754             errors and stop processing, as in
2755              
2756             use Log::Log4perl qw(:easy) ;
2757             Log::Log4perl->easy_init($DEBUG);
2758            
2759             shaky_function() or LOGDIE "It failed!";
2760              
2761             there's a cosmetic problem: The message gets printed twice:
2762              
2763             2005/07/10 18:37:14 It failed!
2764             It failed! at ./t line 12
2765              
2766             The obvious solution is to use LOGEXIT() instead of LOGDIE(), but there's
2767             also a special tag for Log4perl that suppresses the second message:
2768              
2769             use Log::Log4perl qw(:no_extra_logdie_message);
2770              
2771             This causes logdie() and logcroak() to call exit() instead of die(). To
2772             modify the script exit code in these occasions, set the variable
2773             C<$Log::Log4perl::LOGEXIT_CODE> to the desired value, the default is 1.
2774              
2775             =item Redefine values without causing errors
2776              
2777             Log4perl's configuration file parser has a few basic safety mechanisms to
2778             make sure configurations are more or less sane.
2779              
2780             One of these safety measures is catching redefined values. For example, if
2781             you first write
2782              
2783             log4perl.category = WARN, Logfile
2784              
2785             and then a couple of lines later
2786              
2787             log4perl.category = TRACE, Logfile
2788              
2789             then you might have unintentionally overwritten the first value and Log4perl
2790             will die on this with an error (suspicious configurations always throw an
2791             error). Now, there's a chance that this is intentional, for example when
2792             you're lumping together several configuration files and actually I<want>
2793             the first value to overwrite the second. In this case use
2794              
2795             use Log::Log4perl qw(:nostrict);
2796              
2797             to put Log4perl in a more permissive mode.
2798              
2799             =item Prevent croak/confess from stringifying
2800              
2801             The logcroak/logconfess functions stringify their arguments before
2802             they pass them to Carp's croak/confess functions. This can get in the
2803             way if you want to throw an object or a hashref as an exception, in
2804             this case use:
2805              
2806             $Log::Log4perl::STRINGIFY_DIE_MESSAGE = 0;
2807              
2808             eval {
2809             # throws { foo => "bar" }
2810             # without stringification
2811             $logger->logcroak( { foo => "bar" } );
2812             };
2813              
2814             =back
2815              
2816             =head1 EXAMPLE
2817              
2818             A simple example to cut-and-paste and get started:
2819              
2820             use Log::Log4perl qw(get_logger);
2821            
2822             my $conf = q(
2823             log4perl.category.Bar.Twix = WARN, Logfile
2824             log4perl.appender.Logfile = Log::Log4perl::Appender::File
2825             log4perl.appender.Logfile.filename = test.log
2826             log4perl.appender.Logfile.layout = \
2827             Log::Log4perl::Layout::PatternLayout
2828             log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
2829             );
2830            
2831             Log::Log4perl::init(\$conf);
2832            
2833             my $logger = get_logger("Bar::Twix");
2834             $logger->error("Blah");
2835              
2836             This will log something like
2837              
2838             2002/09/19 23:48:15 t1 25> Blah
2839              
2840             to the log file C<test.log>, which Log4perl will append to or
2841             create it if it doesn't exist already.
2842              
2843             =head1 INSTALLATION
2844              
2845             If you want to use external appenders provided with C<Log::Dispatch>,
2846             you need to install C<Log::Dispatch> (2.00 or better) from CPAN,
2847             which itself depends on C<Attribute-Handlers> and
2848             C<Params-Validate>. And a lot of other modules, that's the reason
2849             why we're now shipping Log::Log4perl with its own standard appenders
2850             and only if you wish to use additional ones, you'll have to go through
2851             the C<Log::Dispatch> installation process.
2852              
2853             Log::Log4perl needs C<Test::More>, C<Test::Harness> and C<File::Spec>,
2854             but they already come with fairly recent versions of perl.
2855             If not, everything's automatically fetched from CPAN if you're using the CPAN
2856             shell (CPAN.pm), because they're listed as dependencies.
2857              
2858             C<Time::HiRes> (1.20 or better) is required only if you need the
2859             fine-grained time stamps of the C<%r> parameter in
2860             C<Log::Log4perl::Layout::PatternLayout>.
2861              
2862             Manual installation works as usual with
2863              
2864             perl Makefile.PL
2865             make
2866             make test
2867             make install
2868              
2869             =head1 DEVELOPMENT
2870              
2871             Log::Log4perl is still being actively developed. We will
2872             always make sure the test suite (approx. 500 cases) will pass, but there
2873             might still be bugs. please check L<http://github.com/mschilli/log4perl>
2874             for the latest release. The api has reached a mature state, we will
2875             not change it unless for a good reason.
2876              
2877             Bug reports and feedback are always welcome, just email them to our
2878             mailing list shown in the AUTHORS section. We're usually addressing
2879             them immediately.
2880              
2881             =head1 REFERENCES
2882              
2883             =over 4
2884              
2885             =item [1]
2886              
2887             Michael Schilli, "Retire your debugger, log smartly with Log::Log4perl!",
2888             Tutorial on perl.com, 09/2002,
2889             L<http://www.perl.com/pub/a/2002/09/11/log4perl.html>
2890              
2891             =item [2]
2892              
2893             Ceki Gülcü, "Short introduction to log4j",
2894             L<http://logging.apache.org/log4j/1.2/manual.html>
2895              
2896             =item [3]
2897              
2898             Vipan Singla, "Don't Use System.out.println! Use Log4j.",
2899             L<http://www.vipan.com/htdocs/log4jhelp.html>
2900              
2901             =item [4]
2902              
2903             The Log::Log4perl project home page: L<http://log4perl.com>
2904              
2905             =back
2906              
2907             =head1 SEE ALSO
2908              
2909             L<Log::Log4perl::Config|Log::Log4perl::Config>,
2910             L<Log::Log4perl::Appender|Log::Log4perl::Appender>,
2911             L<Log::Log4perl::Layout::PatternLayout|Log::Log4perl::Layout::PatternLayout>,
2912             L<Log::Log4perl::Layout::SimpleLayout|Log::Log4perl::Layout::SimpleLayout>,
2913             L<Log::Log4perl::Level|Log::Log4perl::Level>,
2914             L<Log::Log4perl::JavaMap|Log::Log4perl::JavaMap>
2915             L<Log::Log4perl::NDC|Log::Log4perl::NDC>,
2916              
2917             =head1 AUTHORS
2918              
2919             Please contribute patches to the project on Github:
2920              
2921             http://github.com/mschilli/log4perl
2922              
2923             Send bug reports or requests for enhancements to the authors via our
2924              
2925             MAILING LIST (questions, bug reports, suggestions/patches):
2926             log4perl-devel@lists.sourceforge.net
2927              
2928             Authors (please contact them via the list above, not directly):
2929             Mike Schilli <m@perlmeister.com>,
2930             Kevin Goess <cpan@goess.org>
2931              
2932             Contributors (in alphabetical order):
2933             Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
2934             Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
2935             Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
2936             Grundman, Paul Harrington, Alexander Hartmaier, David Hull,
2937             Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
2938             Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope,
2939             Lars Thegler, David Viner, Mac Yang.
2940              
2941             =head1 LICENSE
2942              
2943             Copyright 2002-2013 by Mike Schilli E<lt>m@perlmeister.comE<gt>
2944             and Kevin Goess E<lt>cpan@goess.orgE<gt>.
2945              
2946             This library is free software; you can redistribute it and/or modify
2947             it under the same terms as Perl itself.
2948