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