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