home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / doc / liblog-log4perl-perl / README < prev   
Encoding:
Text File  |  2010-07-21  |  85.9 KB  |  2,118 lines

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