home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Log4perl.pm < prev    next >
Encoding:
Perl POD Document  |  2003-05-17  |  68.8 KB  |  1,965 lines

  1. ##################################################
  2. package Log::Log4perl;
  3. ##################################################
  4.  
  5. use 5.006;
  6. use strict;
  7. use warnings;
  8.  
  9. use Log::Dispatch::Base;
  10. use Log::Log4perl::Logger;
  11. use Log::Log4perl::Level;
  12. use Log::Log4perl::Config;
  13. use Log::Dispatch::Screen;
  14. use Log::Log4perl::Appender;
  15.  
  16. use constant DEBUG => 1;
  17.  
  18. our $VERSION = '0.32';
  19.  
  20.    # set this to '1' if you're using a wrapper
  21.    # around Log::Log4perl
  22. our $caller_depth = 0;
  23.  
  24.     #this is a mapping of convenience names to opcode masks used in
  25.     #$ALLOWED_CODE_OPS_IN_CONFIG_FILE below
  26. our %ALLOWED_CODE_OPS = (
  27.     'safe'        => [ ':browse' ],
  28.     'restrictive' => [ ':default' ],
  29. );
  30.  
  31.     #set this to the opcodes which are allowed when
  32.     #$ALLOW_CODE_IN_CONFIG_FILE is set to a true value
  33.     #if undefined, there are no restrictions on code that can be
  34.     #excuted
  35. our @ALLOWED_CODE_OPS_IN_CONFIG_FILE;
  36.  
  37.     #this hash lists things that should be exported into the Safe
  38.     #compartment.  The keys are the package the symbol should be
  39.     #exported from and the values are array references to the names
  40.     #of the symbols (including the leading type specifier)
  41. our %VARS_SHARED_WITH_SAFE_COMPARTMENT = (
  42.     main => [ '%ENV' ],
  43. );
  44.  
  45.     #setting this to a true value will allow Perl code to be executed
  46.     #within the config file.  It works in conjunction with
  47.     #$ALLOWED_CODE_OPS_IN_CONFIG_FILE, which if defined restricts the
  48.     #opcodes which can be executed using the 'Safe' module.
  49.     #setting this to a false value disables code execution in the
  50.     #config file
  51. our $ALLOW_CODE_IN_CONFIG_FILE = 1;
  52.  
  53.     #arrays in a log message will be joined using this character,
  54.     #see Log::Log4perl::Appender::DBI
  55. our $JOIN_MSG_ARRAY_CHAR = '';
  56.  
  57. ##################################################
  58. sub import {
  59. ##################################################
  60.     my($class) = shift;
  61.  
  62.     no strict qw(refs);
  63.  
  64.     my $caller_pkg = caller();
  65.  
  66.     my(%tags) = map { $_ => 1 } @_;
  67.  
  68.         # Lazy man's logger
  69.     if(exists $tags{':easy'}) {
  70.         $tags{':levels'} = 1;
  71.         $tags{':nowarn'} = 1;
  72.         $tags{'get_logger'} = 1;
  73.     }
  74.  
  75.     if(exists $tags{get_logger}) {
  76.         # Export get_logger into the calling module's 
  77.  
  78.         *{"$caller_pkg\::get_logger"} = *get_logger;
  79.  
  80.         delete $tags{get_logger};
  81.     }
  82.  
  83.     if(exists $tags{':levels'}) {
  84.         # Export log levels ($DEBUG, $INFO etc.) from Log4perl::Level
  85.         my $caller_pkg = caller();
  86.  
  87.         for my $key (keys %Log::Log4perl::Level::PRIORITY) {
  88.             my $name  = "$caller_pkg\::$key";
  89.                # Need to split this up in two lines, or CVS will
  90.                # mess it up.
  91.             my $value = $
  92.                         Log::Log4perl::Level::PRIORITY{$key};
  93.             *{"$name"} = \$value;
  94.         }
  95.  
  96.         delete $tags{':levels'};
  97.     }
  98.  
  99.         # Lazy man's logger
  100.     if(exists $tags{':easy'}) {
  101.         delete $tags{':easy'};
  102.  
  103.             # Define default logger object in caller's package
  104.         my $logger = get_logger("$caller_pkg");
  105.         my $string = "\$${caller_pkg}::_default_logger = \$logger";
  106.         eval $string or die "$@";
  107.  
  108.             # Define DEBUG, INFO, etc. routines in caller's package
  109.         for(qw(DEBUG INFO WARN ERROR FATAL)) {
  110.             my $level   = $_;
  111.             my $lclevel = lc($_);
  112.             *{"$caller_pkg\::$_"} = sub { 
  113.                 Log::Log4perl::Logger::init_warn() unless 
  114.                                $Log::Log4perl::Logger::INITIALIZED;
  115.                 $logger->{$level}->($logger, @_, $level);
  116.             };
  117.         }
  118.  
  119.             # Define LOGDIE, LOGWARN
  120.  
  121.         *{"$caller_pkg\::LOGDIE"} = sub {
  122.             Log::Log4perl::Logger::init_warn() unless 
  123.                            $Log::Log4perl::Logger::INITIALIZED;
  124.             $logger->{FATAL}->($logger, @_, "FATAL");
  125.             CORE::die(Log::Log4perl::Logger::callerline(join '', @_));
  126.         };
  127.  
  128.         *{"$caller_pkg\::LOGWARN"} = sub { 
  129.             Log::Log4perl::Logger::init_warn() unless 
  130.                            $Log::Log4perl::Logger::INITIALIZED;
  131.             $logger->{WARN}->($logger, @_, "WARN");
  132.             CORE::warn(Log::Log4perl::Logger::callerline(join '', @_));
  133.         };
  134.     }
  135.  
  136.     if(exists $tags{':nowarn'}) {
  137.         $Log::Log4perl::Logger::INITIALIZED = 1;
  138.         delete $tags{':nowarn'};
  139.     }
  140.  
  141.     if(keys %tags) {
  142.         # We received an Option we couldn't understand.
  143.         die "Unknown Option(s): @{[keys %tags]}";
  144.     }
  145. }
  146.  
  147. ##################################################
  148. sub initialized {
  149. ##################################################
  150.     return $Log::Log4perl::Logger::INITIALIZED;
  151. }
  152.  
  153. ##################################################
  154. sub new {
  155. ##################################################
  156.     die "THIS CLASS ISN'T FOR DIRECT USE. " .
  157.         "PLEASE CHECK 'perldoc " . __PACKAGE__ . "'.";
  158. }
  159.  
  160. ##################################################
  161. sub reset { # Mainly for debugging/testing
  162. ##################################################
  163.     # Delegate this to the logger ...
  164.     return Log::Log4perl::Logger->reset();
  165. }
  166.  
  167. ##################################################
  168. sub init { # Read the config file
  169. ##################################################
  170.     my($class, @args) = @_;
  171.  
  172.     #woops, they called ::init instead of ->init, let's be forgiving
  173.     if ($class ne __PACKAGE__) {
  174.         unshift(@args, $class);
  175.     }
  176.  
  177.     # Delegate this to the config module
  178.     return Log::Log4perl::Config->init(@args);
  179. }
  180.  
  181. ##################################################
  182. sub init_and_watch { 
  183. ##################################################
  184.     my($class, @args) = @_;
  185.  
  186.     #woops, they called ::init instead of ->init, let's be forgiving
  187.     if ($class ne __PACKAGE__) {
  188.         unshift(@args, $class);
  189.     }
  190.  
  191.     # Delegate this to the config module
  192.     return Log::Log4perl::Config->init_and_watch(@args);
  193. }
  194.  
  195.  
  196. ##################################################
  197. sub easy_init { # Initialize the root logger with a screen appender
  198. ##################################################
  199.     my($class, @args) = @_;
  200.  
  201.     # Did somebody call us with Log::Log4perl::easy_init()?
  202.     if(ref($class) or $class =~ /^\d+$/) {
  203.         unshift @args, $class;
  204.     }
  205.  
  206.     my @loggers = ();
  207.  
  208.     my %default = ( level    => $DEBUG,
  209.                     file     => "STDERR",
  210.                     category => "",
  211.                     layout   => "%d %m%n",
  212.                   );
  213.  
  214.     if(!@args) {
  215.         push @loggers, \%default;
  216.     } else {
  217.         for my $arg (@args) {
  218.             if($arg =~ /^\d+$/) {
  219.                 my %logger = (%default, level => $arg);
  220.                 push @loggers, \%logger;
  221.             } elsif(ref($arg) eq "HASH") {
  222.                 my %logger = (%default, %$arg);
  223.                 push @loggers, \%logger;
  224.             }
  225.         }
  226.     }
  227.  
  228.     for my $logger (@loggers) {
  229.  
  230.         my $app;
  231.  
  232.         if($logger->{file} =~ /^stderr$/i) {
  233.             $app = Log::Log4perl::Appender->new("Log::Dispatch::Screen");
  234.         } elsif($logger->{file} =~ /^stdout$/i) {
  235.             $app = Log::Log4perl::Appender->new("Log::Dispatch::Screen",
  236.                                                 stderr => 0);
  237.         } elsif($logger->{file} =~ /^(>)?(>)?/) {
  238.             my $mode = ($2 ? "append" : "write");
  239.             $logger->{file} =~ s/>+//g;
  240.             $app = Log::Log4perl::Appender->new("Log::Dispatch::File",
  241.                 filename => $logger->{file},
  242.                 mode     => $mode);
  243.         }
  244.  
  245.         my $layout = Log::Log4perl::Layout::PatternLayout->new(
  246.                                                         $logger->{layout});
  247.         $app->layout($layout);
  248.  
  249.         my $log = Log::Log4perl->get_logger($logger->{category});
  250.         $log->level($logger->{level});
  251.         $log->add_appender($app);
  252.     }
  253. }
  254.  
  255. ##################################################
  256. sub get_logger {  # Get an instance (shortcut)
  257. ##################################################
  258.     my($class, @args) = @_;
  259.  
  260.     if(!defined $class) {
  261.         # Called as ::get_logger()
  262.         unshift(@args, scalar caller());
  263.     } elsif($class eq __PACKAGE__ and !defined $args[0]) {
  264.         # Called as ->get_logger()
  265.         unshift(@args, scalar caller());
  266.     } elsif($class ne __PACKAGE__) {
  267.         # Called as ::get_logger($category)
  268.         unshift(@args, $class);
  269.     } else {
  270.         # Called as ->get_logger($category)
  271.     }
  272.  
  273.     # Delegate this to the logger module
  274.     return Log::Log4perl::Logger->get_logger(@args);
  275. }
  276.  
  277. 1;
  278.  
  279. __END__
  280.  
  281. =head1 NAME
  282.  
  283. Log::Log4perl - Log4j implementation for Perl
  284.  
  285. =head1 SYNOPSIS
  286.  
  287.     Log::Log4perl::init('/etc/log4perl.conf');
  288.     
  289.     --or--
  290.     
  291.     Log::Log4perl::init_and_watch('/etc/log4perl.conf',10);
  292.     
  293.     --then--
  294.     
  295.     
  296.     $logger = Log::Log4perl->get_logger('house.bedrm.desk.topdrwr');
  297.     
  298.     $logger->debug('this is a debug message');
  299.     $logger->info('this is an info message');
  300.     $logger->warn('etc');
  301.     $logger->error('..');
  302.     $logger->fatal('..');
  303.     
  304.     #####/etc/log4perl.conf###################
  305.     log4perl.logger.house              = WARN,  FileAppndr1
  306.     log4perl.logger.house.bedroom.desk = DEBUG,  FileAppndr1
  307.     
  308.     log4perl.appender.FileAppndr1          = Log::Dispatch::File
  309.     log4perl.appender.FileAppndr1.filename = desk.log 
  310.     log4perl.appender.FileAppndr1.layout   = \
  311.                             Log::Log4perl::Layout::SimpleLayout
  312.     ###########################################
  313.        
  314. =head1 ABSTRACT
  315.  
  316.     Log::Log4perl provides a powerful logging API to your application
  317.  
  318. =head1 DESCRIPTION
  319.  
  320. Log::Log4perl lets you remote-control and fine-tune the logging behaviour
  321. of your system from the outside. It implements the widely popular 
  322. (Java-based) Log4j logging package in pure Perl. 
  323.  
  324. B<For a detailed tutorial on Log::Log4perl usage, please read [1]>.
  325.  
  326. A WORD OF CAUTION: Log::Log4perl IS STILL UNDER DEVELOPMENT. WE WILL
  327. ALWAYS MAKE SURE THE TEST SUITE (approx. 350 CASES) WILL PASS, BUT THERE 
  328. MIGHT STILL BE BUGS. PLEASE CHECK http://log4perl.sourceforge.net REGULARILY
  329. FOR THE LATEST RELEASE. THE API HAS REACHED A MATURE STATE, WE WILL 
  330. NOT CHANGE IT UNLESS FOR A GOOD REASON. 
  331.  
  332. Logging beats a debugger if you want to know what's going on 
  333. in your code during runtime. However, traditional logging packages
  334. are too static and generate a flood of log messages in your log files
  335. that won't help you.
  336.  
  337. C<Log::Log4perl> is different. It allows you to control the amount of 
  338. logging messages generated at three different levels:
  339.  
  340. =over 4
  341.  
  342. =item *
  343.  
  344. At a central location in your system (either in a configuration file or
  345. in the startup code) you specify I<which components> (classes, functions) 
  346. of your system should generate logs.
  347.  
  348. =item *
  349.  
  350. You specify how detailed the logging of these components should be by
  351. specifying logging I<levels>.
  352.  
  353. =item *
  354.  
  355. You also specify which so-called I<appenders> you want to feed your
  356. log messages to ("Print it to the screen and also append it to /tmp/my.log")
  357. and which format ("Write the date first, then the file name and line 
  358. number, and then the log message") they should be in.
  359.  
  360. =back
  361.  
  362. This is a very powerful and flexible mechanism. You can turn on and off
  363. your logs at any time, specify the level of detail and make that
  364. dependent on the subsystem that's currently executed. 
  365.  
  366. Let me give you an example: You might 
  367. find out that your system has a problem in the 
  368. C<MySystem::Helpers::ScanDir>
  369. component. Turning on detailed debugging logs all over the system would
  370. generate a flood of useless log messages and bog your system down beyond
  371. recognition. With C<Log::Log4perl>, however, you can tell the system:
  372. "Continue to log only severe errors in the log file. Open a second
  373. log file, turn on full debug logs in the C<MySystem::Helpers::ScanDir>
  374. component and dump all messages originating from there into the new
  375. log file". And all this is possible by just changing the parameters
  376. in a configuration file, which your system can re-read even 
  377. while it's running!
  378.  
  379. =head1 How to use it
  380.  
  381. The C<Log::Log4perl> package can be initialized in two ways: Either
  382. via Perl commands or via a C<log4j>-style configuration file.
  383.  
  384. =head2 Initialize via a configuration file
  385.  
  386. This is the easiest way to prepare your system for using
  387. C<Log::Log4perl>. Use a configuration file like this:
  388.  
  389.     ############################################################
  390.     # A simple root logger with a Log::Dispatch file appender
  391.     # in Perl.
  392.     # Mike Schilli 2002 m@perlmeister.com
  393.     ############################################################
  394.     log4perl.rootLogger=ERROR, LOGFILE
  395.     
  396.     log4perl.appender.LOGFILE=Log::Dispatch::File
  397.     log4perl.appender.LOGFILE.filename=/var/log/myerrs.log
  398.     log4perl.appender.LOGFILE.mode=append
  399.     
  400.     log4perl.appender.LOGFILE.layout=PatternLayout
  401.     log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n
  402.  
  403. These lines define your standard logger that's appending severe
  404. errors to C</var/log/myerrs.log>, using the format
  405.  
  406.     [millisecs] source-filename line-number class - message newline
  407.  
  408. Check L<Configuration files> for more details on how to control
  409. your loggers using a configuration file.
  410.  
  411. Assuming that this file is saved as C<log.conf>, you need to 
  412. read it in in the startup section of your code, using the following
  413. commands:
  414.  
  415.   use Log::Log4perl;
  416.   Log::Log4perl->init("log.conf");
  417.  
  418. After that's done I<somewhere> in the code, you can retrieve
  419. logger objects I<anywhere> in the code. Note that
  420. there's no need to carry any logger references around with your 
  421. functions and methods. You can get a logger anytime via a singleton
  422. mechanism:
  423.  
  424.     package My::MegaPackage;
  425.  
  426.     sub some_method {
  427.         my($param) = @_;
  428.  
  429.         use  Log::Log4perl;
  430.         my $log = Log::Log4perl->get_logger("My::MegaPackage");
  431.  
  432.         $log->debug("Debug message");
  433.         $log->info("Info message");
  434.         $log->error("Error message");
  435.  
  436.         ...
  437.     }
  438.  
  439. With the configuration file above, C<Log::Log4perl> will write
  440. "Error message" to the specified log file, but won't do anything for 
  441. the C<debug()> and C<info()> calls, because the log level has been set
  442. to C<ERROR> for all components in the first line of 
  443. configuration file shown above.
  444.  
  445. Why C<Log::Log4perl-E<gt>get_logger> and
  446. not C<Log::Log4perl-E<gt>new>? We don't want to create a new
  447. object every time. Usually in OO-Programming, you create an object
  448. once and use the reference to it to call its methods. However,
  449. this requires that you pass around the object to all functions
  450. and the last thing we want is pollute each and every function/method
  451. we're using with a handle to the C<Logger>:
  452.  
  453.     sub function {  # Brrrr!!
  454.         my($logger, $some, $other, $parameters) = @_;
  455.     }
  456.  
  457. Instead, if a function/method wants a reference to the logger, it
  458. just calls the Logger's static C<get_logger()> method to obtain
  459. a reference to the I<one and only> possible logger object of
  460. a certain category.
  461. That's called a I<singleton> if you're a Gamma fan.
  462.  
  463. How does the logger know
  464. which messages it is supposed to log and which ones to suppress?
  465. C<Log::Log4perl> works with inheritence: The config file above didn't 
  466. specify anything about C<My::MegaPackage>. 
  467. And yet, we've defined a logger of the category 
  468. C<My::MegaPackage>.
  469. In this case, C<Log::Log4perl> will walk up the class hierarchy
  470. (C<My> and then the we're at the root) to figure out if a log level is
  471. defined somewhere. In the case above, the log level at the root
  472. (root I<always> defines a log level, but not necessary an appender)
  473. defines that 
  474. the log level is supposed to be C<ERROR> -- meaning that I<debug>
  475. and I<info> messages are suppressed.
  476.  
  477. =head2 Configuration within Perl
  478.  
  479. Initializing the logger can certainly also be done from within Perl.
  480. At last, this is what C<Log::Log4perl::Config> does behind the scenes.
  481. At the Perl level, we can specify exactly, which loggers work with
  482. which appenders and which layouts.
  483.  
  484. Here's the code for a root logger which sends error and
  485. higher prioritized messages to the C</tmp/my.log> logfile:
  486.  
  487.   # Initialize the logger
  488.  
  489.   use Log::Log4perl qw(:levels);
  490.   use Log::Dispatch::Screen;
  491.   use Log::Log4perl::Appender;
  492.  
  493.   my $app = Log::Log4perl::Appender->new("Log::Dispatch::Screen");
  494.   my $layout = Log::Log4perl::Layout::PatternLayout
  495.                                         ->new("%d> %F %L %m %n");
  496.   $app->layout($layout);
  497.  
  498.   my $logger = Log::Log4perl->get_logger("My.Component");
  499.   $logger->level($INFO);
  500.   $logger->add_appender($app);
  501.  
  502. And after this, we can, again, start logging I<anywhere> in the system
  503. like this (remember, we don't want to pass around references, so
  504. we just get the logger via the singleton-mechanism):
  505.  
  506.   # Use the logger
  507.  
  508.   use Log::Log4perl;
  509.   my $log = Log::Log4perl->get_logger("My::Component");
  510.   $log->debug("Debug Message");  # Suppressed
  511.   $log->info("Info Message");    # Printed
  512.   $log->error("Error Message");  # Printed
  513.  
  514. =head2 Log Levels
  515.  
  516. There's five predefined log levels: C<FATAL>, C<ERROR>, C<WARN>, C<INFO> 
  517. and C<DEBUG> (in descending priority). Your configured logging level
  518. has to at least match the priority of the logging message.
  519.  
  520. If your configured logging level is C<WARN>, then messages logged 
  521. with C<info()> and C<debug()> message will be suppressed. 
  522. C<fatal()>, C<error()> and C<warn()> will make their way through,
  523. because their priority is higher or equal than the configured setting.
  524.  
  525. Instead of calling the methods
  526.  
  527.     $logger->debug("...");  # Log a debug message
  528.     $logger->info("...");   # Log a info message
  529.     $logger->warn("...");   # Log a warn message
  530.     $logger->error("...");  # Log a error message
  531.     $logger->fatal("...");  # Log a fatal message
  532.  
  533. you could also call the C<log()> method with the appropriate level
  534. using the constants defined in C<Log::Log4perl::Level>:
  535.  
  536.     use Log::Log4perl::Level;
  537.  
  538.     $logger->log($DEBUG, "...");
  539.     $logger->log($INFO, "...");
  540.     $logger->log($WARN, "...");
  541.     $logger->log($ERROR, "...");
  542.     $logger->log($FATAL, "...");
  543.  
  544. But nobody does that, really. Neither does anyone need more logging
  545. levels than these predefined ones. If you think you do, I would
  546. suggest you look into steering your logging behaviour via
  547. the category mechanism.
  548.  
  549. If you need to find out if the currently configured logging
  550. level would allow a logger's logging statement to go through, use the
  551. logger's C<is_I<level>()> methods:
  552.  
  553.     $logger->is_debug()    # True if debug messages would go through
  554.     $logger->is_info()     # True if info messages would go through
  555.     $logger->is_warn()     # True if warn messages would go through
  556.     $logger->is_error()    # True if error messages would go through
  557.     $logger->is_fatal()    # True if fatal messages would go through
  558.  
  559. Example: C<$logger-E<gt>is_warn()> returns true if the logger's current
  560. level, as derived from either the logger's category (or, in absence of
  561. that, one of the logger's parent's level setting) is 
  562. C<$WARN>, C<$ERROR> or C<$FATAL>.
  563.  
  564. These level checking functions
  565. will come in handy later, when we want to block unnecessary
  566. expensive parameter construction in case the logging level is too
  567. low to log the statement anyway, like in:
  568.  
  569.     if($logger->is_error()) {
  570.         $logger->error("Erroneous array: @super_long_array");
  571.     }
  572.  
  573. If we had just written
  574.  
  575.     $logger->error("Erroneous array: @super_long_array");
  576.  
  577. then Perl would have interpolated
  578. C<@super_long_array> into the string via an expensive operation
  579. only to figure out shortly after that the string can be ignored
  580. entirely because the configured logging level is lower than C<$ERROR>.
  581.  
  582. The to-be-logged
  583. message passed to all of the functions described above can
  584. consist of an arbitrary number of arguments, which the logging functions
  585. just chain together to a single string. Therefore
  586.  
  587.     $logger->debug("Hello ", "World", "!");  # and
  588.     $logger->debug("Hello World!");
  589.  
  590. are identical.
  591.  
  592. =head2 Log and die or warn
  593.  
  594. Often, when you croak / carp / warn / die, you want to log those messages.
  595. Rather than doing the following:
  596.  
  597.     $logger->fatal($err) && die($err);
  598.  
  599. you can use the following:
  600.  
  601.     $logger->logwarn();
  602.     $logger->logdie();
  603.  
  604. These print out log messages in the WARN and FATAL level, respectively,
  605. and then call the built-in warn() and die() functions. Since there is
  606. an ERROR level between WARN and FATAL, there are two additional helper
  607. functions in case you'd like to use ERROR for either warn() or die():
  608.  
  609.     $logger->error_warn();
  610.     $logger->error_die();
  611.  
  612. Finally, there's the Carp functions that do just what the Carp functions
  613. do, but with logging:
  614.  
  615.     $logger->logcarp();        # warn w/ 1-level stack trace
  616.     $logger->logcluck();       # warn w/ full stack trace
  617.     $logger->logcroak();       # die w/ 1-level stack trace
  618.     $logger->logconfess();     # die w/ full stack trace
  619.  
  620. =head2 Appenders
  621.  
  622. If you don't define any appenders, nothing will happen. Appenders will
  623. be triggered whenever the configured logging level requires a message
  624. to be logged and not suppressed.
  625.  
  626. C<Log::Log4perl> doesn't define any appenders by default, not even the root
  627. logger has one.
  628.  
  629. C<Log::Log4perl> utilizes I<Dave Rolskys> excellent C<Log::Dispatch>
  630. module to implement a wide variety of different appenders. You can have
  631. your messages written to STDOUT, to a file or to a database -- or to
  632. all of them at once if you desire to do so.
  633.  
  634. Here's the list of appender modules currently available via C<Log::Dispatch>:
  635.  
  636.        Log::Log4perl::Appender::DBI (by Kevin Goess)
  637.        Log::Dispatch::ApacheLog
  638.        Log::Dispatch::DBI (by Tatsuhiko Miyagawa)
  639.        Log::Dispatch::Email,
  640.        Log::Dispatch::Email::MailSend,
  641.        Log::Dispatch::Email::MailSendmail,
  642.        Log::Dispatch::Email::MIMELite
  643.        Log::Dispatch::File
  644.        Log::Dispatch::FileRotate (by Mark Pfeiffer)
  645.        Log::Dispatch::Handle
  646.        Log::Dispatch::Screen
  647.        Log::Dispatch::Syslog
  648.        Log::Dispatch::Tk (by Dominique Dumont)
  649.  
  650. For additional information on appenders, please check the
  651. L<Log::Log4perl::Appender> manual page.
  652.  
  653. Now let's assume that we want to go overboard and log C<info()> or
  654. higher prioritized messages in the C<My::Category> class
  655. to both STDOUT and to a log file, say C</tmp/my.log>.
  656. In the initialisation section of your system,
  657. just define two appenders using the readily available
  658. C<Log::Dispatch::File> and C<Log::Dispatch::Screen> modules
  659. via the C<Log::Log4perl::Appender> wrapper:
  660.  
  661.   ########################
  662.   # Initialisation section
  663.   ########################
  664.   use Log::Log4perl;
  665.   use Log::Log4perl::Layout;
  666.   use Log::Log4perl::Level;
  667.  
  668.      # Define a category logger
  669.   my $log = Log::Log4perl->get_logger("My::Category");
  670.  
  671.      # Define a layout
  672.   my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
  673.  
  674.      # Define a file appender
  675.   my $file_appender = Log::Log4perl::Appender->new(
  676.                           "Log::Dispatch::File",
  677.                           name      => "filelog",
  678.                           filename  => "/tmp/my.log");
  679.  
  680.  
  681.      # Define a stdout appender
  682.   my $stdout_appender =  Log::Log4perl::Appender->new(
  683.                           "Log::Dispatch::Screen",
  684.                           name      => "screenlog",
  685.                           stderr    => 0);
  686.  
  687.      # Have both appenders use the same layout (could be different)
  688.   $stdout_appender->layout($layout);
  689.   $file_appender->layout($layout);
  690.  
  691.   $log->add_appender($stdout_appender);
  692.   $log->add_appender($file_appender);
  693.   $log->level($INFO);
  694.  
  695. Please note the class of the C<Log::Dispatch> object is passed as a
  696. I<string> to C<Log::Log4perl::Appender> in the I<first> argument. 
  697. Behind the scenes, C<Log::Log4perl::Appender> will create the necessary
  698. C<Log::Dispatch::*> object and pass along the name value pairs we provided
  699. to C<Log::Log4perl::Appender-E<gt>new()> after the first argument.
  700.  
  701. The C<name> value is optional and if you don't provide one,
  702. C<Log::Log4perl::Appender-E<gt>new()> will create a unique one for you.
  703. The names and values of additional parameters are dependent on the requirements
  704. of the particular C<Log::Dispatch::*> class and can be looked up in their
  705. manual pages.
  706.  
  707. On a side note: In case you're wondering if
  708. C<Log::Log4perl::Appender-E<gt>new()> will also take care of the
  709. C<min_level> argument to the C<Log::Dispatch::*> constructors called
  710. behind the scenes -- yes, it does. This is because we want the
  711. C<Log::Dispatch> objects to blindly log everything we send them
  712. (C<debug> is their lowest setting) because I<we> in C<Log::Log4perl>
  713. want to call the shots and decide on when and what to log.
  714.  
  715. The call to the appender's I<layout()> method specifies the format (as a
  716. previously created C<Log::Log4perl::PatternLayout> object) in which the
  717. message is being logged in the specified appender. The format shown
  718. above is logging not only the message but also the number of
  719. milliseconds since the program has started (%r), the name of the file
  720. the call to the logger has happened and the line number there (%F and
  721. %L), the message itself (%m) and a OS-specific newline character (%n).
  722. For more detailed info on layout formats, see L<Log Layouts>. If you
  723. don't specify a layout, the logger will fall back to
  724. C<Log::Log4perl::SimpleLayout>, which logs the debug level, a hyphen (-)
  725. and the log message.
  726.  
  727. Once the initialisation shown above has happened once, typically in
  728. the startup code of your system, just use this logger anywhere in 
  729. your system (or better yet, only in C<My::Category>, since we
  730. defined it this way) as often as you like:
  731.  
  732.   ##########################
  733.   # ... in some function ...
  734.   ##########################
  735.   my $log = Log::Log4perl->get_logger("My::Category");
  736.   $log->info("This is an informational message");
  737.  
  738. Above, we chose to define a I<category> logger (C<My::Category>)
  739. in a specific way. This will cause only messages originating from
  740. this specific category logger to be logged in the defined format
  741. and locations.
  742.  
  743. Instead, 
  744. we could have configured the I<root> logger with the appenders and layout
  745. shown above. Now
  746.  
  747.   ##########################
  748.   # ... in some function ...
  749.   ##########################
  750.   my $log = Log::Log4perl->get_logger("My::Category");
  751.   $log->info("This is an informational message");
  752.  
  753. will trigger a logger with no layout or appenders or even a level
  754. defined. This logger, however, will inherit the level from categories up
  755. the hierarchy -- ultimately the root logger, since there's no C<My>
  756. logger. Once it detects that it needs to log a message, it will first
  757. try to find its own appenders (which it doesn't have any of) and then
  758. walk up the hierarchy (first C<My>, then C<root>) to call any appenders
  759. defined there.
  760.  
  761. This will result in exactly the same behaviour as shown above -- with the 
  762. exception that other category loggers could also use the root logger's 
  763. appenders and layouts, but could certainly define their own categories
  764. and levels.
  765.  
  766. =head2 Turn off a component
  767.  
  768. C<Log4perl> doesn't only allow you to selectively switch I<on> a category
  769. of log messages, you can also use the mechanism to selectively I<disable>
  770. logging in certain components whereas logging is kept turned on in higher-level
  771. categories. This mechanism comes in handy if you find that while bumping 
  772. up the logging level of a high-level (i. e. close to root) category, 
  773. that one component logs more than it should, 
  774.  
  775. Here's how it works: 
  776.  
  777.     ############################################################
  778.     # Turn off logging in a lower-level category while keeping
  779.     # it active in higher-level categories.
  780.     ############################################################
  781.     log4perl.rootLogger=debug, LOGFILE
  782.     log4perl.logger.deep.down.the.hierarchy = error, LOGFILE
  783.  
  784.     # ... Define appenders ...
  785.  
  786. This way, log messages issued from within 
  787. C<Deep::Down::The::Hierarchy> and below will be
  788. logged only if they're C<error> or worse, while in all other system components
  789. even C<debug> messages will be logged.
  790.  
  791. =head2 Configuration files
  792.  
  793. As shown above, you can define C<Log::Log4perl> loggers both from within
  794. your Perl code or from configuration files. The latter have the unbeatable
  795. advantage that you can modify your system's logging behaviour without 
  796. interfering with the code at all. So even if your code is being run by 
  797. somebody who's totally oblivious to Perl, they still can adapt the
  798. module's logging behaviour to their needs.
  799.  
  800. C<Log::Log4perl> has been designed to understand C<Log4j> configuration
  801. files -- as used by the original Java implementation. Instead of 
  802. reiterating the format description in [2], let me just list three
  803. examples (also derived from [2]), which should also illustrate
  804. how it works:
  805.  
  806.     log4j.rootLogger=DEBUG, A1
  807.     log4j.appender.A1=org.apache.log4j.ConsoleAppender
  808.     log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  809.     log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n
  810.  
  811. This enables messages of priority C<debug> or higher in the root
  812. hierarchy and has the system write them to the console. 
  813. C<ConsoleAppender> is a Java appender, but C<Log::Log4perl> jumps
  814. through a significant number of hoops internally to map these to their
  815. corresponding Perl classes, C<Log::Dispatch::Screen> in this case.
  816.  
  817. Second example:
  818.  
  819.     log4perl.rootLogger=DEBUG, A1
  820.     log4perl.appender.A1=Log::Dispatch::Screen
  821.     log4perl.appender.A1.layout=PatternLayout
  822.     log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n
  823.     log4perl.logger.com.foo=WARN
  824.  
  825. This defines two loggers: The root logger and the C<com.foo> logger.
  826. The root logger is easily triggered by debug-messages, 
  827. but the C<com.foo> logger makes sure that messages issued within
  828. the C<Com::Foo> component and below are only forwarded to the appender
  829. if they're of priority I<warning> or higher. 
  830.  
  831. Note that the C<com.foo> logger doesn't define an appender. Therefore,
  832. it will just propagate the message up the hierarchy until the root logger
  833. picks it up and forwards it to the one and only appender of the root
  834. category, using the format defined for it.
  835.  
  836. Third example:
  837.  
  838.     log4j.rootLogger=debug, stdout, R
  839.     log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  840.     log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  841.     log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n
  842.     log4j.appender.R=org.apache.log4j.RollingFileAppender
  843.     log4j.appender.R.File=example.log
  844.     log4j.appender.R.layout=org.apache.log4j.PatternLayout
  845.     log4j.appender.R.layout.ConversionPattern=%p %c - %m%n
  846.  
  847. The root logger defines two appenders here: C<stdout>, which uses 
  848. C<org.apache.log4j.ConsoleAppender> (ultimately mapped by C<Log::Log4perl>
  849. to C<Log::Dispatch::Screen>) to write to the screen. And
  850. C<R>, a C<org.apache.log4j.RollingFileAppender> 
  851. (mapped by C<Log::Log4perl> to 
  852. C<Log::Dispatch::FileRotate> with the C<File> attribute specifying the
  853. log file.
  854.  
  855. See L<Log::Log4perl::Config> for more examples and syntax explanations.
  856.  
  857. =head2 Log Layouts
  858.  
  859. If the logging engine passes a message to an appender, because it thinks
  860. it should be logged, the appender doesn't just
  861. write it out haphazardly. There's ways to tell the appender how to format
  862. the message and add all sorts of interesting data to it: The date and
  863. time when the event happened, the file, the line number, the
  864. debug level of the logger and others.
  865.  
  866. There's currently two layouts defined in C<Log::Log4perl>: 
  867. C<Log::Log4perl::Layout::SimpleLayout> and
  868. C<Log::Log4perl::Layout::Patternlayout>:
  869.  
  870. =over 4 
  871.  
  872. =item C<Log::Log4perl::SimpleLayout> 
  873.  
  874. formats a message in a simple
  875. way and just prepends it by the debug level and a hyphen:
  876. C<"$level - $message>, for example C<"FATAL - Can't open password file">.
  877.  
  878. =item C<Log::Log4perl::PatternLayout> 
  879.  
  880. on the other hand is very powerful and 
  881. allows for a very flexible format in C<printf>-style. The format
  882. string can contain a number of placeholders which will be
  883. replaced by the logging engine when it's time to log the message:
  884.  
  885.     %c Category of the logging event.
  886.     %C Fully qualified package (or class) name of the caller
  887.     %d Current date in yyyy/MM/dd hh:mm:ss format
  888.     %F File where the logging event occurred
  889.     %H Hostname
  890.     %l Fully qualified name of the calling method followed by the
  891.        callers source the file name and line number between 
  892.        parentheses.
  893.     %L Line number within the file where the log statement was issued
  894.     %m The message to be logged
  895.     %M Method or function where the logging request was issued
  896.     %n Newline (OS-independent)
  897.     %p Priority of the logging event
  898.     %P pid of the current process
  899.     %r Number of milliseconds elapsed from program start to logging 
  900.        event
  901.     %x The elements of the NDC stack (see below)
  902.     %X{key} The entry 'key' of the MDC (see below)
  903.     %% A literal percent (%) sign
  904.  
  905. NDC and MDC are explained in L<"Nested Diagnostic Context (NDC)">
  906. and L<"Mapped Diagnostic Context (MDC)">.
  907.  
  908. Also, C<%d> can be fine-tuned to display only certain characteristics
  909. of a date, according to the SimpleDateFormat in the Java World
  910. (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html)
  911.  
  912. In this way, C<%d{HH:mm}> displays only hours and minutes of the current date,
  913. while C<%d{yy, EEEE}> displays a two-digit year, followed by a spelled-out
  914. (like C<Wednesday>). 
  915.  
  916. Similar options are available for shrinking the displayed category or
  917. limit file/path components, C<%F{1}> only displays the source file I<name>
  918. without any path components while C<%F> logs the full path. %c{2} only
  919. logs the last two components of the current category, C<Foo::Bar::Baz> 
  920. becomes C<Bar::Baz> and saves space.
  921.  
  922. If those placeholders aren't enough, then you can define your own right in
  923. the config file like this:
  924.  
  925.     log4perl.PatternLayout.cspec.U = sub { return "UID $<" }
  926.  
  927. See L<Log::Log4perl::Layout::PatternLayout> for further details on
  928. customized specifiers.
  929.  
  930. Please note that the subroutines you're defining in this way are going
  931. to be run in the C<main> namespace, so be sure to fully qualify functions
  932. and variables if they're located in different packages.
  933.     
  934. SECURITY NOTE: this feature means arbitrary perl code can be embedded in the 
  935. config file.  In the rare case where the people who have access to your config 
  936. file are different from the people who write your code and shouldn't have 
  937. execute rights, you might want to call
  938.  
  939.     Log::Log4perl::Config->allow_code(0);
  940.  
  941. before you call init(). Alternatively you can supply a restricted set of
  942. Perl opcodes that can be embedded in the config file as described in
  943. L<"Restricting what Opcodes can be in a Perl Hook">.
  944.  
  945. =back
  946.  
  947. All placeholders are quantifiable, just like in I<printf>. Following this 
  948. tradition, C<%-20c> will reserve 20 chars for the category and left-justify it.
  949.  
  950. Layouts are objects, here's how you create them:
  951.  
  952.         # Create a simple layout
  953.     my $simple = Log::Log4perl::SimpleLayout();
  954.  
  955.         # create a flexible layout:
  956.         # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\n")
  957.     my $pattern = Log::Log4perl::PatternLayout("%d (%F:%L)> %m%n");
  958.  
  959. Every appender has exactly one layout assigned to it. You assign
  960. the layout to the appender using the appender's C<layout()> object:
  961.  
  962.     my $app =  Log::Log4perl::Appender->new(
  963.                   "Log::Dispatch::Screen",
  964.                   name      => "screenlog",
  965.                   stderr    => 0);
  966.  
  967.         # Assign the previously defined flexible layout
  968.     $app->layout($pattern);
  969.  
  970.         # Add the appender to a previously defined logger
  971.     $logger->add_appender($app);
  972.  
  973.         # ... and you're good to go!
  974.     $logger->debug("Blah");
  975.         # => "2002/07/10 23:55:35 (test.pl:207)> Blah\n"
  976.  
  977. If you don't specify a layout for an appender, the logger will fall back 
  978. to C<SimpleLayout>.
  979.  
  980. For more details on logging and how to use the flexible and the simple
  981. format, check out the original C<log4j> website under
  982.  
  983.     http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/SimpleLayout.html
  984.     http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
  985.  
  986. =head2 Penalties
  987.  
  988. Logging comes with a price tag. C<Log::Log4perl> is currently being optimized
  989. to allow for maximum performance, both with logging enabled and disabled.
  990.  
  991. But you need to be aware that there's a small hit every time your code
  992. encounters a log statement -- no matter if logging is enabled or not. 
  993. C<Log::Log4perl> has been designed to keep this so low that it will
  994. be unnoticable to most applications.
  995.  
  996. Here's a couple of tricks which help C<Log::Log4perl> to avoid
  997. unnecessary delays:
  998.  
  999. You can save serious time if you're logging something like
  1000.  
  1001.         # Expensive in non-debug mode!
  1002.     for (@super_long_array) {
  1003.         $logger->debug("Element: $_\n");
  1004.     }
  1005.  
  1006. and C<@super_long_array> is fairly big, so looping through it is pretty
  1007. expensive. Only you, the programmer, knows that going through that C<for>
  1008. loop can be skipped entirely if the current logging level for the 
  1009. actual component is higher than C<debug>.
  1010. In this case, use this instead:
  1011.  
  1012.         # Cheap in non-debug mode!
  1013.     if($logger->is_debug()) {
  1014.         for (@super_long_array) {
  1015.             $logger->debug("Element: $_\n");
  1016.         }
  1017.     }
  1018.  
  1019. If you're afraid that the way you're generating the parameters to the
  1020. of the logging function is fairly expensive, use closures:
  1021.  
  1022.         # Passed as subroutine ref
  1023.     use Data::Dumper;
  1024.     $logger->debug(sub { Dumper($data) } );
  1025.  
  1026. This won't unravel C<$data> via Dumper() unless it's actually needed
  1027. because it's logged. 
  1028.  
  1029. Also, Log::Log4perl lets you specify arguments
  1030. to logger functions in I<message output filter syntax>:
  1031.  
  1032.     $logger->debug("Structure: ",
  1033.                    { filter => \&Dumper,
  1034.                      value  => $someref });
  1035.  
  1036. In this way, shortly before Log::Log4perl sending the
  1037. message out to any appenders, it will be searching all arguments for
  1038. hash references and treat them in a special way:
  1039.  
  1040. It will invoke the function given as a reference with the C<filter> key
  1041. (C<Data::Dumper::Dumper()>) and pass it the value that came with
  1042. the key named C<value> as an argument.
  1043. The anonymous hash in the call above will be replaced by the return 
  1044. value of the filter function.
  1045.  
  1046. =head1 Categories
  1047.  
  1048. C<Log::Log4perl> uses I<categories> to determine if a log statement in
  1049. a component should be executed or suppressed at the current logging level.
  1050. Most of the time, these categories are just the classes the log statements
  1051. are located in:
  1052.  
  1053.     package Candy::Twix;
  1054.  
  1055.     sub new { 
  1056.         my $logger = Log::Log4perl->new("Candy::Twix");
  1057.         $logger->debug("Creating a new Twix bar");
  1058.         bless {}, shift;
  1059.     }
  1060.  
  1061.     # ...
  1062.  
  1063.     package Candy::Snickers;
  1064.  
  1065.     sub new { 
  1066.         my $logger = Log::Log4perl->new("Candy.Snickers");
  1067.         $logger->debug("Creating a new Snickers bar");
  1068.         bless {}, shift;
  1069.     }
  1070.  
  1071.     # ...
  1072.  
  1073.     package main;
  1074.     Log::Log4perl->init("mylogdefs.conf") or 
  1075.         die "Whoa, cannot read mylogdefs.conf!";
  1076.  
  1077.         # => "LOG> Creating a new Snickers bar"
  1078.     my $first = Candy::Snickers->new();
  1079.         # => "LOG> Creating a new Twix bar"
  1080.     my $second = Candy::Twix->new();
  1081.  
  1082. Note that you can separate your category hierarchy levels
  1083. using either dots like
  1084. in Java (.) or double-colons (::) like in Perl. Both notations
  1085. are equivalent and are handled the same way internally.
  1086.  
  1087. However, categories are just there to make
  1088. use of inheritance: if you invoke a logger in a sub-category, 
  1089. it will bubble up the hierarchy and call the appropriate appenders.
  1090. Internally, categories are not related to the class hierarchy of the program
  1091. at all -- they're purely virtual. You can use arbitrary categories --
  1092. for example in the following program, which isn't oo-style, but
  1093. procedural:
  1094.  
  1095.     sub print_portfolio {
  1096.  
  1097.         my $log = Log::Log4perl->new("user.portfolio");
  1098.         $log->debug("Quotes requested: @_");
  1099.  
  1100.         for(@_) {
  1101.             print "$_: ", get_quote($_), "\n";
  1102.         }
  1103.     }
  1104.  
  1105.     sub get_quote {
  1106.  
  1107.         my $log = Log::Log4perl->new("internet.quotesystem");
  1108.         $log->debug("Fetching quote: $_[0]");
  1109.  
  1110.         return yahoo_quote($_[0]);
  1111.     }
  1112.  
  1113. The logger in first function, C<print_portfolio>, is assigned the
  1114. (virtual) C<user.portfolio> category. Depending on the C<Log4perl>
  1115. configuration, this will either call a C<user.portfolio> appender,
  1116. a C<user> appender, or an appender assigned to root -- without
  1117. C<user.portfolio> having any relevance to the class system used in 
  1118. the program.
  1119. The logger in the second function adheres to the 
  1120. C<internet.quotesystem> category -- again, maybe because it's bundled 
  1121. with other Internet functions, but not because there would be
  1122. a class of this name somewhere.
  1123.  
  1124. However, be careful, don't go overboard: if you're developing a system
  1125. in object-oriented style, using the class hierarchy is usually your best
  1126. choice. Think about the people taking over your code one day: The
  1127. class hierarchy is probably what they know right up front, so it's easy
  1128. for them to tune the logging to their needs.
  1129.  
  1130. =head2 Return Values
  1131.  
  1132. All logging methods return values indicating if their message
  1133. actually reached one or more appenders. If the message has been
  1134. suppressed because of level constraints, C<undef> is returned.
  1135.  
  1136. For example,
  1137.  
  1138.     my $ret = $logger->info("Message");
  1139.  
  1140. will return C<undef> if the system debug level for the current category
  1141. is not C<INFO> or more permissive. 
  1142. If Log::Log4perl
  1143. forwarded the message to one or more appenders, the number of appenders
  1144. is returned.
  1145.  
  1146. If appenders decide to veto on the message with an appender threshold,
  1147. the log method's return value will have them excluded. This means that if
  1148. you've got one appender holding an appender threshold and you're 
  1149. logging a message
  1150. which passes the system's log level hurdle but not the appender threshold,
  1151. C<0> will be returned by the log function.
  1152.  
  1153. The bottom line is: Logging functions will return a I<true> value if the message
  1154. made it through to one or more appenders and a I<false> value if it didn't.
  1155. This allows for constructs like
  1156.  
  1157.     $logger->fatal("@_") or print STDERR "@_\n";
  1158.  
  1159. which will ensure that the fatal message isn't lost
  1160. if the current level is lower than FATAL or printed twice if 
  1161. the level is acceptable but an appender already points to STDERR.
  1162.  
  1163. =head2 Pitfalls with Categories
  1164.  
  1165. Be careful with just blindly reusing the system's packages as
  1166. categories. If you do, you'll get into trouble with inherited methods.
  1167. Imagine the following class setup:
  1168.  
  1169.     use Log::Log4perl;
  1170.  
  1171.     ###########################################
  1172.     package Bar;
  1173.     ###########################################
  1174.     sub new {
  1175.         my($class) = @_;
  1176.         my $logger = Log::Log4perl::get_logger(__PACKAGE__);
  1177.         $logger->debug("Creating instance");
  1178.         bless {}, $class;
  1179.     }
  1180.     ###########################################
  1181.     package Bar::Twix;
  1182.     ###########################################
  1183.     our @ISA = qw(Bar);
  1184.  
  1185.     ###########################################
  1186.     package main;
  1187.     ###########################################
  1188.     Log::Log4perl->init(\ qq{
  1189.     log4perl.category.Bar.Twix = DEBUG, Screen
  1190.     log4perl.appender.Screen = Log::Dispatch::Screen
  1191.     log4perl.appender.Screen.layout = SimpleLayout
  1192.     });
  1193.  
  1194.     my $bar = Bar::Twix->new();
  1195.  
  1196. C<Bar::Twix> just inherits everything from C<Bar>, including the constructor
  1197. C<new()>.
  1198. Contrary to what you might be thinking at first, this won't log anything. 
  1199. Reason for this is the C<get_logger()> call in package C<Bar>, which
  1200. will always get a logger of the C<Bar> category, even if we call C<new()> via
  1201. the C<Bar::Twix> package, which will make perl go up the inheritance 
  1202. tree to actually execute C<Bar::new()>. Since we've only defined logging
  1203. behaviour for C<Bar::Twix> in the configuration file, nothing will happen.
  1204.  
  1205. This can be fixed by changing the C<get_logger()> method in C<Bar::new()>
  1206. to obtain a logger of the category matching the
  1207. I<actual> class of the object, like in
  1208.  
  1209.         # ... in Bar::new() ...
  1210.     my $logger = Log::Log4perl::get_logger($class);
  1211.  
  1212. This way, you'll make sure the logger logs appropriately, 
  1213. no matter if the method is inherited or called directly.
  1214. C<new()> always gets the
  1215. real class name as an argument and all other methods can determine it 
  1216. via C<ref($self)>), so it shouldn't be a problem to get the right class
  1217. every time.
  1218.  
  1219. =head1 Custom Filters
  1220.  
  1221. Log4perl allows the use of customized filters in its appenders
  1222. to control the output of messages. These filters might grep for
  1223. certain text chunks in a message, verify that its priority
  1224. matches or exceeds a certain level or that this is the 10th
  1225. time the same message has been submitted -- and come to a log/no log 
  1226. decision based upon these circumstantial facts.
  1227.  
  1228. Check out L<Log::Log4perl::Filter> for detailed instructions 
  1229. on how to use them.
  1230.  
  1231. =head1 Cool Tricks
  1232.  
  1233. =head2 Shortcuts
  1234.  
  1235. When getting an instance of a logger, instead of saying
  1236.  
  1237.     use Log::Log4perl;
  1238.     my $logger = Log::Log4perl->get_logger();
  1239.  
  1240. it's often more convenient to import the C<get_logger> method from 
  1241. C<Log::Log4perl> into the current namespace:
  1242.  
  1243.     use Log::Log4perl qw(get_logger);
  1244.     my $logger = get_logger();
  1245.  
  1246. =head2 Alternative initialization
  1247.  
  1248. Instead of having C<init()> read in a configuration file, you can 
  1249. also pass in a reference to a string, containing the content of
  1250. the file:
  1251.  
  1252.     Log::Log4perl->init( \$config_text );
  1253.  
  1254. Also, if you've got the C<name=value> pairs of the configuration in
  1255. a hash, you can just as well initialized C<Log::Log4perl> with
  1256. a reference to it:
  1257.  
  1258.     my %key_value_pairs = (
  1259.         "log4perl.rootLogger"       => "error, LOGFILE",
  1260.         "log4perl.appender.LOGFILE" => "Log::Dispatch::File",
  1261.         ...
  1262.     );
  1263.  
  1264.     Log::Log4perl->init( \%key_value_pairs );
  1265.  
  1266. Or also you can use a URL, see below:
  1267.  
  1268. =head2 Using LWP to parse URLs
  1269.  
  1270. (This section borrowed from XML::DOM::Parser by T.J. Mather).
  1271.  
  1272. The init() function now also supports URLs, e.g. I<http://www.erols.com/enno/xsa.xml>.
  1273. It uses LWP to download the file and then calls parse() on the resulting string.
  1274. By default it will use a L<LWP::UserAgent> that is created as follows:
  1275.  
  1276.  use LWP::UserAgent;
  1277.  $LWP_USER_AGENT = LWP::UserAgent->new;
  1278.  $LWP_USER_AGENT->env_proxy;
  1279.  
  1280. Note that env_proxy reads proxy settings from environment variables, which is what I need to
  1281. do to get thru our firewall. If you want to use a different LWP::UserAgent, you can 
  1282. set it with
  1283.  
  1284.     Log::Log4perl::Config::set_LWP_UserAgent($my_agent);
  1285.  
  1286. Currently, LWP is used when the filename (passed to parsefile) starts with one of
  1287. the following URL schemes: http, https, ftp, wais, gopher, or file (followed by a colon.)
  1288.  
  1289. Don't use this feature with init_and_watch().
  1290.  
  1291.  
  1292. =head2 Perl Hooks in the Configuration File
  1293.  
  1294. If some of the values used in the Log4perl configuration file 
  1295. need to be dynamically modified by the program, use Perl hooks:
  1296.  
  1297.     log4perl.appender.File.filename = \
  1298.         sub { return getLogfileName(); }
  1299.  
  1300. Each value starting with the string C<sub {...> is interpreted as Perl code to
  1301. be executed at the time the application parses the configuration
  1302. via C<Log::Log4perl::init()>. The return value of the subroutine
  1303. is used by Log::Log4perl as the configuration value.
  1304.  
  1305. The Perl code is executed in the C<main> package, functions in
  1306. other packages have to be called in fully-qualified notation.
  1307.  
  1308. Here's another example, utilizing an environment variable as a
  1309. username for a DBI appender:
  1310.  
  1311.     log4perl.appender.DB.username = \
  1312.         sub { $ENV{DB_USER_NAME } }
  1313.  
  1314. However, please note the difference between these code snippets and those
  1315. used for user-defined conversion specifiers as discussed in
  1316. L<Log::Log4perl::PatternLayout>: While the snippets above are run I<once>
  1317. when C<Log::Log4perl::init()> is called, the conversion specifier
  1318. snippets are executed I<each time> a message is rendered according to
  1319. the PatternLayout.
  1320.  
  1321. SECURITY NOTE: this feature means arbitrary perl code can be embedded in the 
  1322. config file.  In the rare case where the people who have access to your config 
  1323. file are different from the people who write your code and shouldn't have 
  1324. execute rights, you might want to set
  1325.  
  1326.     Log::Log4perl::Config->allow_code(0);
  1327.  
  1328. before you call init().  Alternatively you can supply a restricted set of
  1329. Perl opcodes that can be embedded in the config file as described in
  1330. L<"Restricting what Opcodes can be in a Perl Hook">.
  1331.  
  1332. =head2 Restricting what Opcodes can be in a Perl Hook
  1333.  
  1334. The value you pass to Log::Log4perl::Config->allow_code() determines whether
  1335. the code that is embedded in the config file is eval'd unrestricted, or
  1336. eval'd in a Safe compartment.  By default, a value of '1' is assumed,
  1337. which does a normal 'eval' without any restrictions. A value of '0' 
  1338. however prevents any embedded code from being evaluated.
  1339.  
  1340. If you would like fine-grained control over what can and cannot be included
  1341. in embedded code, then please utilize the following methods:
  1342.  
  1343.  Log::Log4perl::Config->allow_code( $allow );
  1344.  Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... );
  1345.  Log::Log4perl::Config->vars_shared_with_safe_compartment( [ \%vars | $package, \@vars ] );
  1346.  Log::Log4perl::Config->allowed_code_ops_convenience_map( [ \%map | $name, \@mask ] );
  1347.  
  1348. Log::Log4perl::Config-E<gt>allowed_code_ops() takes a list of opcode masks
  1349. that are allowed to run in the compartment.  The opcode masks must be
  1350. specified as described in L<Opcode>:
  1351.  
  1352.  Log::Log4perl::Config->allowed_code_ops(':subprocess');
  1353.  
  1354. This example would allow Perl operations like backticks, system, fork, and
  1355. waitpid to be executed in the compartment.  Of course, you probably don't
  1356. want to use this mask -- it would allow exactly what the Safe compartment is
  1357. designed to prevent.
  1358.  
  1359. Log::Log4perl::Config-E<gt>vars_shared_with_safe_compartment() 
  1360. takes the symbols which
  1361. should be exported into the Safe compartment before the code is evaluated. 
  1362. The keys of this hash are the package names that the symbols are in, and the
  1363. values are array references to the literal symbol names.  For convenience,
  1364. the default settings export the '%ENV' hash from the 'main' package into the
  1365. compartment:
  1366.  
  1367.  Log::Log4perl::Config->vars_shared_with_safe_compartment(
  1368.    main => [ '%ENV' ],
  1369.  );
  1370.  
  1371. Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map() is an accessor
  1372. method to a map of convenience names to opcode masks. At present, the
  1373. following convenience names are defined:
  1374.  
  1375.  safe        = [ ':browse' ]
  1376.  restrictive = [ ':default' ]
  1377.  
  1378. For convenience, if Log::Log4perl::Config-E<gt>allow_code() is called with a
  1379. value which is a key of the map previously defined with
  1380. Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map(), then the
  1381. allowed opcodes are set according to the value defined in the map. If this
  1382. is confusing, consider the following:
  1383.  
  1384.  use Log::Log4perl;
  1385.  
  1386.  my $config = <<'END';
  1387.   log4perl.logger = INFO, Main
  1388.   log4perl.appender.Main = Log::Dispatch::File
  1389.   log4perl.appender.Main.filename = \
  1390.       sub { "example" . getpwuid($<) . ".log" }
  1391.   log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout
  1392.  END
  1393.  
  1394.  $Log::Log4perl::Config->allow_code('restrictive');
  1395.  Log::Log4perl->init( \$config );       # will fail
  1396.  $Log::Log4perl::Config->allow_code('safe');
  1397.  Log::Log4perl->init( \$config );       # will succeed
  1398.  
  1399. The reason that the first call to -E<gt>init() fails is because the
  1400. 'restrictive' name maps to an opcode mask of ':default'.  getpwuid() is not
  1401. part of ':default', so -E<gt>init() fails.  The 'safe' name maps to an opcode
  1402. mask of ':browse', which allows getpwuid() to run, so -E<gt>init() succeeds.
  1403.  
  1404. allowed_code_ops_convenience_map() can be invoked in several ways:
  1405.  
  1406. =over 4
  1407.  
  1408. =item allowed_code_ops_convenience_map()
  1409.  
  1410. Returns the entire convenience name map as a hash reference in scalar
  1411. context or a hash in list context.
  1412.  
  1413. =item allowed_code_ops_convenience_map( \%map )
  1414.  
  1415. Replaces the entire conveniece name map with the supplied hash reference.
  1416.  
  1417. =item allowed_code_ops_convenience_map( $name )
  1418.  
  1419. Returns the opcode mask for the given convenience name, or undef if no such
  1420. name is defined in the map.
  1421.  
  1422. =item allowed_code_ops_convenience_map( $name, \@mask )
  1423.  
  1424. Adds the given name/mask pair to the convenience name map.  If the name
  1425. already exists in the map, it's value is replaced with the new mask.
  1426.  
  1427. =back 
  1428.  
  1429. as can vars_shared_with_safe_compartment():
  1430.  
  1431. =over 4
  1432.  
  1433. =item vars_shared_with_safe_compartment()
  1434.  
  1435. Return the entire map of packages to variables as a hash reference in scalar
  1436. context or a hash in list context.
  1437.  
  1438. =item vars_shared_with_safe_compartment( \%packages )
  1439.  
  1440. Replaces the entire map of packages to variables with the supplied hash
  1441. reference.
  1442.  
  1443. =item vars_shared_with_safe_compartment( $package )
  1444.  
  1445. Returns the arrayref of variables to be shared for a specific package.
  1446.  
  1447. =item vars_shared_with_safe_compartment( $package, \@vars )
  1448.  
  1449. Adds the given package / varlist pair to the map.  If the package already
  1450. exists in the map, it's value is replaced with the new arrayref of variable
  1451. names.
  1452.  
  1453. =back
  1454.  
  1455. For more information on opcodes and Safe Compartments, see L<Opcode> and
  1456. L<Safe>.
  1457.  
  1458. =head2 Incrementing and Decrementing the Log Levels
  1459.  
  1460. Log4perl provides some internal functions for quickly adjusting the
  1461. log level from within a running Perl program. 
  1462.  
  1463. Now, some people might
  1464. argue that you should adjust your levels from within an external 
  1465. Log4perl configuration file, but Log4perl is everybody's darling.
  1466.  
  1467. Typically run-time adjusting of levels is done
  1468. at the beginning, or in response to some external input (like a
  1469. "more logging" runtime command for diagnostics).
  1470.  
  1471. To increase the level of logging currently being done, use:
  1472.  
  1473.     $logger->more_logging($delta);
  1474.  
  1475. and to decrease it, use:
  1476.  
  1477.     $logger->less_logging($delta);
  1478.  
  1479. $delta must be a positive integer (for now, we may fix this later ;).
  1480.  
  1481. There are also two equivalent functions:
  1482.  
  1483.     $logger->inc_level($delta);
  1484.     $logger->dec_level($delta);
  1485.  
  1486. They're included to allow you a choice in readability. Some folks
  1487. will prefer more/less_logging, as they're fairly clear in what they
  1488. do, and allow the programmer not to worry too much about what a Level
  1489. is and whether a higher Level means more or less logging. However,
  1490. other folks who do understand and have lots of code that deals with
  1491. levels will probably prefer the inc_level() and dec_level() methods as
  1492. they want to work with Levels and not worry about whether that means
  1493. more or less logging. :)
  1494.  
  1495. That diatribe aside, typically you'll use more_logging() or inc_level()
  1496. as such:
  1497.  
  1498.     my $v = 0; # default level of verbosity.
  1499.     
  1500.     GetOptions("v+" => \$v, ...);
  1501.  
  1502.     $logger->more_logging($v);  # inc logging level once for each -v in ARGV
  1503.  
  1504. =head2 Custom Log Levels
  1505.  
  1506. First off, let me tell you that creating custom levels is heavily
  1507. deprecated by the log4j folks. Indeed, instead of creating additional
  1508. levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL, 
  1509. you should use categories to control the amount of logging smartly,
  1510. based on the location of the log-active code in the system.
  1511.  
  1512. Nevertheless, 
  1513. Log4perl provides a nice way to create custom levels via the 
  1514. create_custom_level() routine function. However, this must be done
  1515. before the first call to init() or get_logger(). Say you want to create
  1516. a NOTIFY logging level that comes after WARN (and thus before INFO).
  1517. You'd do such as follows:
  1518.  
  1519.     use Log::Log4perl;
  1520.     use Log::Log4perl::Level;
  1521.  
  1522.     Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN");
  1523.  
  1524. And that's it! create_custom_level() creates the following functions /
  1525. variables for level FOO:
  1526.  
  1527.     $FOO_INT        # integer to use in toLevel()
  1528.     $logger->foo()  # log function to log if level = FOO
  1529.     $logger->is_foo()   # true if current level is >= FOO
  1530.  
  1531. These levels can also be used in your
  1532. config file, but note that your config file probably won't be
  1533. portable to another log4perl or log4j environment unless you've
  1534. made the appropriate mods there too.
  1535.  
  1536. =head2 System-wide log levels
  1537.  
  1538. As a fairly drastic measure to decrease (or increase) the logging level
  1539. all over the system with one single configuration option, use the C<threshold>
  1540. keyword in the Log4perl configuration file:
  1541.  
  1542.     log4perl.threshold = ERROR
  1543.  
  1544. sets the system-wide (or hierarchy-wide according to the log4j documentation)
  1545. to ERROR and therefore deprives every logger in the system of the right 
  1546. to log lower-prio messages.
  1547.  
  1548. =head2 Easy Mode
  1549.  
  1550. For teaching purposes (especially for [1]), I've put C<:easy> mode into 
  1551. C<Log::Log4perl>, which just initializes a single root logger with a 
  1552. defined priority and a screen appender including some nice standard layout:
  1553.  
  1554.     ### Initialization Section
  1555.     use Log::Log4perl qw(:easy);
  1556.     Log::Log4perl->easy_init($ERROR);  # Set priority of root logger to ERROR
  1557.  
  1558.     ### Application Section
  1559.     my $logger = get_logger();
  1560.     $logger->fatal("This will get logged.");
  1561.     $logger->debug("This won't.");
  1562.  
  1563. This will dump something like
  1564.  
  1565.     2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.
  1566.  
  1567. to the screen. While this has been proven to work well familiarizing people
  1568. with C<Log::Logperl> slowly, effectively avoiding to clobber them over the 
  1569. head with a 
  1570. plethora of different knobs to fiddle with (categories, appenders, levels, 
  1571. layout), the overall mission of C<Log::Log4perl> is to let people use
  1572. categories right from the start to get used to the concept. So, let's keep
  1573. this one fairly hidden in the man page (congrats on reading this far :).
  1574.  
  1575. =head2 Stealth loggers
  1576.  
  1577. Sometimes, people are lazy. If you're whipping up a 50-line script and want 
  1578. the comfort of Log::Log4perl without having the burden of carrying a
  1579. separate log4perl.conf file or a 5-liner defining that you want to append
  1580. your log statements to a file, you can use the following features:
  1581.  
  1582.     use Log::Log4perl qw(:easy);
  1583.  
  1584.     Log::Log4perl->easy_init( { level   => $DEBUG,
  1585.                                 file    => ">>test.log" } );
  1586.  
  1587.         # Logs to test.log via stealth logger
  1588.     DEBUG("Debug this!");
  1589.     INFO("Info this!");
  1590.     WARN("Warn this!");
  1591.     ERROR("Error this!");
  1592.  
  1593.     some_function();
  1594.  
  1595.     sub some_function {
  1596.             # Same here
  1597.         FATAL("Fatal this!");
  1598.     }
  1599.  
  1600. In C<:easy> mode, C<Log::Log4perl> will instantiate a I<stealth logger>
  1601. named C<$_default_logger> and import it into the current package. Also,
  1602. it will introduce the
  1603. convenience functions C<DEBUG()>, C<INFO()>, C<WARN()>, 
  1604. C<ERROR()> and C<FATAL()> into the package namespace,
  1605. which take arguments and forward them to C<_default_logger-E<gt>debug()>,
  1606. C<_default_logger-E<gt>info()> and so on.
  1607.  
  1608. The C<easy_init> method can be called with a single level value to
  1609. create a STDERR appender and a root logger as in
  1610.  
  1611.     Log::Log4perl->easy_init($DEBUG);
  1612.  
  1613. or, as shown below (and in the example above) 
  1614. with a reference to a hash, specifying values
  1615. for C<level> (the logger's priority), C<file> (the appender's data sink),
  1616. C<category> (the logger's category> and C<layout> for the appender's 
  1617. pattern layout specification.
  1618. All key-value pairs are optional, they 
  1619. default to C<$DEBUG> for C<level>, C<STDERR> for C<file>,
  1620. C<""> (root category) for C<category> and 
  1621. C<%d %m%n> for C<layout>:
  1622.  
  1623.     Log::Log4perl->easy_init( { level    => $DEBUG,
  1624.                                 file     => ">test.log",
  1625.                                 category => "Bar::Twix",
  1626.                                 layout   => '%F{1}-%L-%M: %m%n' } );
  1627.  
  1628. The C<file> parameter takes file names preceded by C<"E<gt>">
  1629. (overwrite) and C<"E<gt>E<gt>"> (append) as arguments. This will
  1630. cause C<Log::Dispatch::File> appenders to be created behind the scenes.
  1631. Also the keywords C<STDOUT> and C<STDERR> (no C<E<gt>> or C<E<gt>E<gt>>)
  1632. are recognized, which will utilize and configure
  1633. C<Log::Dispatch::Screen> appropriately.
  1634.  
  1635. The stealth loggers can be used in different packages, you just need to make
  1636. sure you're calling the "use" function in every package you're using
  1637. C<Log::Log4perl>'s easy services:
  1638.  
  1639.     package Bar::Twix;
  1640.     use Log::Log4perl qw(:easy);
  1641.     sub eat { DEBUG("Twix mjam"); }
  1642.  
  1643.     package Bar::Mars;
  1644.     use Log::Log4perl qw(:easy);
  1645.     sub eat { INFO("Mars mjam"); }
  1646.  
  1647.     package main;
  1648.  
  1649.     use Log::Log4perl qw(:easy);
  1650.  
  1651.     Log::Log4perl->easy_init( { level    => $DEBUG,
  1652.                                 file     => ">>test.log",
  1653.                                 category => "Bar::Twix",
  1654.                                 layout   => '%F{1}-%L-%M: %m%n' },
  1655.                               { level    => $DEBUG,
  1656.                                 file     => "STDOUT",
  1657.                                 category => "Bar::Mars",
  1658.                                 layout   => '%m%n' },
  1659.                             );
  1660.     Bar::Twix::eat();
  1661.     Bar::Mars::eat();
  1662.  
  1663. As shown above, C<easy_init()> will take any number of different logger 
  1664. definitions as hash references.
  1665.  
  1666. Also, stealth loggers feature the functions C<LOGWARN()> and C<LOGDIE()>,
  1667. combining a logging request with a subsequent Perl warn() or die()
  1668. statement. So, for example
  1669.  
  1670.     if($all_is_lost) {
  1671.         LOGDIE("Terrible Problem");
  1672.     }
  1673.  
  1674. will log the message if the package's logger is at least C<FATAL> but
  1675. C<die()> (including the traditional output to STDERR) in any case afterwards.
  1676.  
  1677. See L<"Log and die or warn"> for the similar C<logdie()> and C<logwarn()>
  1678. functions of regular (i.e non-stealth) loggers.
  1679.  
  1680. B<When using Log::Log4perl in easy mode, 
  1681. please make sure you understand the implications of 
  1682. L</"Pitfalls with Categories">>.
  1683.  
  1684. By the way, these convenience functions perform exactly as fast as the 
  1685. standard Log::Log4perl logger methods, there's I<no> performance penalty
  1686. whatsoever.
  1687.  
  1688. =head2 Nested Diagnostic Context (NDC)
  1689.  
  1690. If you find that your application could use a global (thread-specific)
  1691. data stack which your loggers throughout the system have easy access to,
  1692. use Nested Diagnostic Contexts (NDCs). Also check out
  1693. L<"Mapped Diagnostic Context (MDC)">, this might turn out to be even more
  1694. useful.
  1695.  
  1696. For example, when handling a request of a web client, it's probably 
  1697. useful to have the user's IP address available in all log statements
  1698. within code dealing with this particular request. Instead of passing
  1699. this piece of data around between your application functions, you can just
  1700. use the global (but thread-specific) NDC mechanism. It allows you
  1701. to push data pieces (scalars usually) onto its stack via
  1702.  
  1703.     Log::Log4perl::NDC->push("San");
  1704.     Log::Log4perl::NDC->push("Francisco");
  1705.  
  1706. and have your loggers retrieve them again via the "%x" placeholder in
  1707. the PatternLayout. With the stack values above and a PatternLayout format
  1708. like "%x %m%n", the call
  1709.  
  1710.     $logger->debug("rocks");
  1711.  
  1712. will end up as 
  1713.  
  1714.     San Francisco rocks
  1715.  
  1716. in the log appender.
  1717.  
  1718. The stack mechanism allows for nested structures.
  1719. Just make sure that at the end of the request, you either decrease the stack
  1720. one by one by calling
  1721.  
  1722.     Log::Log4perl::NDC->pop();
  1723.     Log::Log4perl::NDC->pop();
  1724.  
  1725. or clear out the entire NDC stack by calling
  1726.  
  1727.     Log::Log4perl::NDC->remove();
  1728.  
  1729. Even if you should forget to do that, C<Log::Log4perl> won't grow the stack
  1730. indefinitely, but limit it to a maximum, defined in C<Log::Log4perl::NDC>
  1731. (currently 5). A call to C<push()> on a full stack will just replace
  1732. the topmost element by the new value.
  1733.  
  1734. Again, the stack is always available via the "%x" placeholder
  1735. in the Log::Log4perl::Layout::PatternLayout class whenever a logger
  1736. fires. It will replace "%x" by the blank-separated list of the
  1737. values on the stack. It does that by just calling
  1738.  
  1739.     Log::Log4perl::NDC->get();
  1740.  
  1741. internally. See details on how this standard log4j feature is implemented
  1742. in L<Log::Log4perl::NDC>.
  1743.  
  1744. =head2 Mapped Diagnostic Context (MDC)
  1745.  
  1746. Just like the previously discussed NDC stores thread-specific
  1747. information in a stack structure, the MDC implements a hash table
  1748. to store key/value pairs in.
  1749.  
  1750. The static method
  1751.  
  1752.     Log::Log4perl::MDC->put($key, $value);
  1753.  
  1754. stores C<$value> under a key C<$key>, with which it can be retrieved later
  1755. (possibly in a totally different part of the system) by calling
  1756. the C<get> method:
  1757.  
  1758.     my $value = Log::Log4perl::MDC->get($key);
  1759.  
  1760. If no value has been stored previously under C<$key>, the C<get> method
  1761. will return the string C<"[undef]"> to allow for easy string interpolation
  1762. later on.
  1763.  
  1764. Typically, MDC values are retrieved later on via the C<"%X{...}"> placeholder
  1765. in C<Log::Log4perl::Layout::PatternLayout>.
  1766. For example, an application taking a web request might store the remote host
  1767. like
  1768.  
  1769.     Log::Log4perl::MDC->put("remote_host", $r->headers("HOST"));
  1770.  
  1771. at its beginning and if the appender's layout looks something like
  1772.  
  1773.     log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n
  1774.  
  1775. then a log statement like
  1776.  
  1777.    DEBUG("Content delivered");
  1778.  
  1779. will log something like
  1780.  
  1781.    adsl-63.dsl.snf.pacbell.net: Content delivered 
  1782.  
  1783. later on in the program.
  1784.  
  1785. For details, please check L<Log::Log4perl::MDC>.
  1786.  
  1787. =head1 How about Log::Dispatch::Config?
  1788.  
  1789. Tatsuhiko Miyagawa's C<Log::Dispatch::Config> is a very clever 
  1790. simplified logger implementation, covering some of the I<log4j>
  1791. functionality. Among the things that 
  1792. C<Log::Log4perl> can but C<Log::Dispatch::Config> can't are:
  1793.  
  1794. =over 4
  1795.  
  1796. =item *
  1797.  
  1798. You can't assign categories to loggers. For small systems that's fine,
  1799. but if you can't turn off and on detailed logging in only a tiny
  1800. subsystem of your environment, you're missing out on a majorly
  1801. useful log4j feature.
  1802.  
  1803. =item *
  1804.  
  1805. Defining appender thresholds. Important if you want to solve problems like
  1806. "log all messages of level FATAL to STDERR, plus log all DEBUG
  1807. messages in C<Foo::Bar> to a log file". If you don't have appenders
  1808. thresholds, there's no way to prevent cluttering STDERR with DEBUG messages.
  1809.  
  1810. =item *
  1811.  
  1812. PatternLayout specifications in accordance with the standard
  1813. (e.g. "%d{HH:mm}").
  1814.  
  1815. =back
  1816.  
  1817. Bottom line: Log::Dispatch::Config is fine for small systems with
  1818. simple logging requirements. However, if you're
  1819. designing a system with lots of subsystems which you need to control
  1820. independantly, you'll love the features of C<Log::Log4perl>,
  1821. which is equally easy to use.
  1822.  
  1823. =head1 Using Log::Log4perl from wrapper classes
  1824.  
  1825. If you don't use C<Log::Log4perl> as described above, 
  1826. but from a wrapper class (like your own Logging class which in turn uses
  1827. C<Log::Log4perl>),
  1828. the pattern layout will generate wrong data for %F, %C, %L and the like.
  1829. Reason for this is that C<Log::Log4perl>'s loggers assume a static
  1830. caller depth to the application that's using them. If you're using
  1831. one (or more) wrapper classes, C<Log::Log4perl> will indicate where
  1832. your logger classes called the loggers, not where your application
  1833. called your wrapper, which is probably what you want in this case.
  1834. But don't dispair, there's a solution: Just increase the value
  1835. of C<$Log::Log4perl::caller_depth> (defaults to 0) by one for every
  1836. wrapper that's in between your application and C<Log::Log4perl>,
  1837. then C<Log::Log4perl> will compensate for the difference.
  1838.  
  1839. =head1 EXAMPLE
  1840.  
  1841. A simple example to cut-and-paste and get started:
  1842.  
  1843.     use Log::Log4perl qw(get_logger);
  1844.     
  1845.     my $conf = q(
  1846.     log4perl.category.Bar.Twix         = WARN, Logfile
  1847.     log4perl.appender.Logfile          = Log::Dispatch::File
  1848.     log4perl.appender.Logfile.filename = test.log
  1849.     log4perl.appender.Logfile.layout = \
  1850.         Log::Log4perl::Layout::PatternLayout
  1851.     log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
  1852.     );
  1853.     
  1854.     Log::Log4perl::init(\$conf);
  1855.     
  1856.     my $logger = get_logger("Bar::Twix");
  1857.     $logger->error("Blah");
  1858.  
  1859. This will log something like
  1860.  
  1861.     2002/09/19 23:48:15 t1 25> Blah 
  1862.  
  1863. to the log file C<test.log>, which Log4perl will append to or 
  1864. create it if it doesn't exist already.
  1865.  
  1866. =head1 INSTALLATION
  1867.  
  1868. C<Log::Log4perl> needs C<Log::Dispatch> (2.00 or better) from CPAN,
  1869. which itself depends on C<Attribute-Handlers> and
  1870. C<Params-Validate>. 
  1871. Everything's automatically fetched from CPAN if you're using the CPAN 
  1872. shell (CPAN.pm), because they're listed as dependencies.
  1873. Also, C<Test::Simple>, C<Test::Harness> and C<File::Spec> are needed,
  1874. but they already come with fairly recent versions of perl.
  1875.  
  1876. C<Time::HiRes> (1.20 or better) is required only if you need the
  1877. fine-grained time stamps of the C<%r> parameter in
  1878. C<Log::Log4perl::Layout::PatternLayout>.
  1879.  
  1880. Manual installation works as usual with
  1881.  
  1882.     perl Makefile.PL
  1883.     make
  1884.     make test
  1885.     make install
  1886.  
  1887. If you're running B<Windows (98, 2000, NT, XP etc.)>, 
  1888. and you're too lazy to rummage through all of 
  1889. Log-Log4perl's dependencies, don't despair: We're providing a PPM package
  1890. which installs easily with your Activestate Perl. Check
  1891. L<Log::Log4perl::FAQ/"how_can_i_install_log__log4perl_on_microsoft_windows">
  1892. for details.
  1893.  
  1894. =head1 DEVELOPMENT
  1895.  
  1896. C<Log::Log4perl> is under heavy development. The latest CVS tarball
  1897. can be obtained from SourceForge, check C<http://log4perl.sourceforge.net>
  1898. for details. Bug reports and feedback are always welcome, just email
  1899. to our mailing list shown in the AUTHORS section.
  1900.  
  1901. =head1 REFERENCES
  1902.  
  1903. =over 4
  1904.  
  1905. =item [1]
  1906.  
  1907. Michael Schilli, "Retire your debugger, log smartly with Log::Log4perl!",
  1908. Tutorial on perl.com, 09/2002, 
  1909. http://www.perl.com/pub/a/2002/09/11/log4perl.html
  1910.  
  1911. =item [2]
  1912.  
  1913. Ceki Gⁿlcⁿ, "Short introduction to log4j",
  1914. http://jakarta.apache.org/log4j/docs/manual.html
  1915.  
  1916. =item [3]
  1917.  
  1918. Vipan Singla, "Don't Use System.out.println! Use Log4j.",
  1919. http://www.vipan.com/htdocs/log4jhelp.html
  1920.  
  1921. =item [4]
  1922.  
  1923. The Log::Log4perl project home page: http://log4perl.sourceforge.net
  1924.  
  1925. =back
  1926.  
  1927. =head1 SEE ALSO
  1928.  
  1929. L<Log::Log4perl::Config|Log::Log4perl::Config>,
  1930. L<Log::Log4perl::Appender|Log::Log4perl::Appender>,
  1931. L<Log::Log4perl::Layout::PatternLayout|Log::Log4perl::Layout::PatternLayout>,
  1932. L<Log::Log4perl::Layout::SimpleLayout|Log::Log4perl::Layout::SimpleLayout>,
  1933. L<Log::Log4perl::Level|Log::Log4perl::Level>,
  1934. L<Log::Log4perl::JavaMap|Log::Log4perl::JavaMap>
  1935. L<Log::Log4perl::NDC|Log::Log4perl::NDC>,
  1936.  
  1937. =head1 AUTHORS
  1938.  
  1939. Please send bug reports or requests for enhancements to the authors via 
  1940. our
  1941.  
  1942.     MAILING LIST (questions, bug reports, suggestions/patches): 
  1943.     log4perl-devel@lists.sourceforge.net
  1944.  
  1945.     Authors (please contact them via the list above, not directly)
  1946.     Mike Schilli <m@perlmeister.com>
  1947.     Kevin Goess <cpan@goess.org>
  1948.  
  1949.     Contributors:
  1950.     Chris R. Donnelly <cdonnelly@digitalmotorworks.com>
  1951.     James FitzGibbon <james.fitzgibbon@target.com>
  1952.     Paul Harrington <Paul-Harrington@deshaw.com>
  1953.     Erik Selberg <erik@selberg.com>
  1954.     Aaron Straup Cope <asc@vineyard.net>
  1955.  
  1956. =head1 COPYRIGHT AND LICENSE
  1957.  
  1958. Copyright 2002 by Mike Schilli E<lt>m@perlmeister.comE<gt> and Kevin Goess
  1959. E<lt>cpan@goess.orgE<gt>.
  1960.  
  1961. This library is free software; you can redistribute it and/or modify
  1962. it under the same terms as Perl itself. 
  1963.  
  1964. =cut
  1965.