1Log::Log4perl(3)      User Contributed Perl Documentation     Log::Log4perl(3)
2
3
4

NAME

6       Log::Log4perl - Log4j implementation for Perl
7

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

ABSTRACT

47           Log::Log4perl provides a powerful logging API for your application
48

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
61       won't 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
67           file 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
76           file name and line number, and then the log message") they should
77           be in.
78
79       This is a very powerful and flexible mechanism. You can turn on and off
80       your logs at any time, specify the level of detail and make that
81       dependent on the subsystem that's currently executed.
82
83       Let me give you an example: You might find out that your system has a
84       problem in the "MySystem::Helpers::ScanDir" component. Turning on
85       detailed debugging logs all over the system would generate a flood of
86       useless log messages and bog your system down beyond recognition. With
87       "Log::Log4perl", however, you can tell the system: "Continue to log
88       only severe errors to the log file. Open a second log file, turn on
89       full debug logs in the "MySystem::Helpers::ScanDir" component and dump
90       all messages originating from there into the new log file". And all
91       this is possible by just changing the parameters in a configuration
92       file, which your system can re-read even while it's running!
93

How to use it

95       The "Log::Log4perl" package can be initialized in two ways: Either via
96       Perl commands or via a "log4j"-style configuration file.
97
98   Initialize via a configuration file
99       This is the easiest way to prepare your system for using
100       "Log::Log4perl". Use a configuration file like this:
101
102           ############################################################
103           # A simple root logger with a Log::Log4perl::Appender::File
104           # file appender in Perl.
105           ############################################################
106           log4perl.rootLogger=ERROR, LOGFILE
107
108           log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
109           log4perl.appender.LOGFILE.filename=/var/log/myerrs.log
110           log4perl.appender.LOGFILE.mode=append
111
112           log4perl.appender.LOGFILE.layout=PatternLayout
113           log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n
114
115       These lines define your standard logger that's appending severe errors
116       to "/var/log/myerrs.log", using the format
117
118           [millisecs] source-filename line-number class - message newline
119
120       Assuming that this configuration file is saved as "log.conf", you need
121       to read it in in the startup section of your code, using the following
122       commands:
123
124         use Log::Log4perl;
125         Log::Log4perl->init("log.conf");
126
127       After that's done somewhere in the code, you can retrieve logger
128       objects anywhere in the code. Note that there's no need to carry any
129       logger references around with your functions and methods. You can get a
130       logger anytime via a singleton mechanism:
131
132           package My::MegaPackage;
133           use  Log::Log4perl;
134
135           sub some_method {
136               my($param) = @_;
137
138               my $log = Log::Log4perl->get_logger("My::MegaPackage");
139
140               $log->debug("Debug message");
141               $log->info("Info message");
142               $log->error("Error message");
143
144               ...
145           }
146
147       With the configuration file above, "Log::Log4perl" will write "Error
148       message" to the specified log file, but won't do anything for the
149       "debug()" and "info()" calls, because the log level has been set to
150       "ERROR" for all components in the first line of configuration file
151       shown above.
152
153       Why "Log::Log4perl->get_logger" and not "Log::Log4perl->new"? We don't
154       want to create a new object every time. Usually in OO-Programming, you
155       create an object once and use the reference to it to call its methods.
156       However, this requires that you pass around the object to all functions
157       and the last thing we want is pollute each and every function/method
158       we're using with a handle to the "Logger":
159
160           sub function {  # Brrrr!!
161               my($logger, $some, $other, $parameters) = @_;
162           }
163
164       Instead, if a function/method wants a reference to the logger, it just
165       calls the Logger's static "get_logger($category)" method to obtain a
166       reference to the one and only possible logger object of a certain
167       category.  That's called a singleton if you're a Gamma fan.
168
169       How does the logger know which messages it is supposed to log and which
170       ones to suppress?  "Log::Log4perl" works with inheritance: The config
171       file above didn't specify anything about "My::MegaPackage".  And yet,
172       we've defined a logger of the category "My::MegaPackage".  In this
173       case, "Log::Log4perl" will walk up the namespace hierarchy ("My" and
174       then we're at the root) to figure out if a log level is defined
175       somewhere. In the case above, the log level at the root (root always
176       defines a log level, but not necessarily an appender) defines that the
177       log level is supposed to be "ERROR" -- meaning that DEBUG and INFO
178       messages are suppressed. Note that this 'inheritance' is unrelated to
179       Perl's class inheritance, it is merely related to the logger namespace.
180
181   Log Levels
182       There are six predefined log levels: "FATAL", "ERROR", "WARN", "INFO",
183       "DEBUG", and "TRACE" (in descending priority). Your configured logging
184       level has to at least match the priority of the logging message.
185
186       If your configured logging level is "WARN", then messages logged with
187       "info()", "debug()", and "trace()" will be suppressed.  "fatal()",
188       "error()" and "warn()" will make their way through, because their
189       priority is higher or equal than the configured setting.
190
191       Instead of calling the methods
192
193           $logger->trace("...");  # Log a trace message
194           $logger->debug("...");  # Log a debug message
195           $logger->info("...");   # Log a info message
196           $logger->warn("...");   # Log a warn message
197           $logger->error("...");  # Log a error message
198           $logger->fatal("...");  # Log a fatal message
199
200       you could also call the "log()" method with the appropriate level using
201       the constants defined in "Log::Log4perl::Level":
202
203           use Log::Log4perl::Level;
204
205           $logger->log($TRACE, "...");
206           $logger->log($DEBUG, "...");
207           $logger->log($INFO, "...");
208           $logger->log($WARN, "...");
209           $logger->log($ERROR, "...");
210           $logger->log($FATAL, "...");
211
212       But nobody does that, really. Neither does anyone need more logging
213       levels than these predefined ones. If you think you do, I would suggest
214       you look into steering your logging behaviour via the category
215       mechanism.
216
217       If you need to find out if the currently configured logging level would
218       allow a logger's logging statement to go through, use the logger's
219       "is_level()" methods:
220
221           $logger->is_trace()    # True if trace messages would go through
222           $logger->is_debug()    # True if debug messages would go through
223           $logger->is_info()     # True if info messages would go through
224           $logger->is_warn()     # True if warn messages would go through
225           $logger->is_error()    # True if error messages would go through
226           $logger->is_fatal()    # True if fatal messages would go through
227
228       Example: "$logger->is_warn()" returns true if the logger's current
229       level, as derived from either the logger's category (or, in absence of
230       that, one of the logger's parent's level setting) is $WARN, $ERROR or
231       $FATAL.
232
233       Also available are a series of more Java-esque functions which return
234       the same values. These are of the format "isLevelEnabled()", so
235       "$logger->isDebugEnabled()" is synonymous to "$logger->is_debug()".
236
237       These level checking functions will come in handy later, when we want
238       to block unnecessary expensive parameter construction in case the
239       logging level is too low to log the statement anyway, like in:
240
241           if($logger->is_error()) {
242               $logger->error("Erroneous array: @super_long_array");
243           }
244
245       If we had just written
246
247           $logger->error("Erroneous array: @super_long_array");
248
249       then Perl would have interpolated @super_long_array into the string via
250       an expensive operation only to figure out shortly after that the string
251       can be ignored entirely because the configured logging level is lower
252       than $ERROR.
253
254       The to-be-logged message passed to all of the functions described above
255       can consist of an arbitrary number of arguments, which the logging
256       functions just chain together to a single string. Therefore
257
258           $logger->debug("Hello ", "World", "!");  # and
259           $logger->debug("Hello World!");
260
261       are identical.
262
263       Note that even if one of the methods above returns true, it doesn't
264       necessarily mean that the message will actually get logged.  What
265       is_debug() checks is that the logger used is configured to let a
266       message of the given priority (DEBUG) through. But after this check,
267       Log4perl will eventually apply custom filters and forward the message
268       to one or more appenders. None of this gets checked by is_xxx(), for
269       the simple reason that it's impossible to know what a custom filter
270       does with a message without having the actual message or what an
271       appender does to a message without actually having it log it.
272
273   Log and die or warn
274       Often, when you croak / carp / warn / die, you want to log those
275       messages.  Rather than doing the following:
276
277           $logger->fatal($err) && die($err);
278
279       you can use the following:
280
281           $logger->logwarn();
282           $logger->logdie();
283
284       These print out log messages in the WARN and FATAL level, respectively,
285       and then call the built-in warn() and die() functions. Since there is
286       an ERROR level between WARN and FATAL, there are two additional helper
287       functions in case you'd like to use ERROR for either warn() or die():
288
289           $logger->error_warn();
290           $logger->error_die();
291
292       Finally, there's the Carp functions that do just what the Carp
293       functions do, but with logging:
294
295           $logger->logcarp();        # warn w/ 1-level stack trace
296           $logger->logcluck();       # warn w/ full stack trace
297           $logger->logcroak();       # die w/ 1-level stack trace
298           $logger->logconfess();     # die w/ full stack trace
299
300   Appenders
301       If you don't define any appenders, nothing will happen. Appenders will
302       be triggered whenever the configured logging level requires a message
303       to be logged and not suppressed.
304
305       "Log::Log4perl" doesn't define any appenders by default, not even the
306       root logger has one.
307
308       "Log::Log4perl" already comes with a standard set of appenders:
309
310           Log::Log4perl::Appender::Screen
311           Log::Log4perl::Appender::ScreenColoredLevels
312           Log::Log4perl::Appender::File
313           Log::Log4perl::Appender::Socket
314           Log::Log4perl::Appender::DBI
315           Log::Log4perl::Appender::Synchronized
316           Log::Log4perl::Appender::RRDs
317
318       to log to the screen, to files and to databases.
319
320       On CPAN, you can find additional appenders like
321
322           Log::Log4perl::Layout::XMLLayout
323
324       by Guido Carls <gcarls@cpan.org>.  It allows for hooking up
325       Log::Log4perl with the graphical Log Analyzer Chainsaw (see "Can I use
326       Log::Log4perl with log4j's Chainsaw?" in Log::Log4perl::FAQ).
327
328   Additional Appenders via Log::Dispatch
329       "Log::Log4perl" also supports Dave Rolskys excellent "Log::Dispatch"
330       framework which implements a wide variety of different appenders.
331
332       Here's the list of appender modules currently available via
333       "Log::Dispatch":
334
335              Log::Dispatch::ApacheLog
336              Log::Dispatch::DBI (by Tatsuhiko Miyagawa)
337              Log::Dispatch::Email,
338              Log::Dispatch::Email::MailSend,
339              Log::Dispatch::Email::MailSendmail,
340              Log::Dispatch::Email::MIMELite
341              Log::Dispatch::File
342              Log::Dispatch::FileRotate (by Mark Pfeiffer)
343              Log::Dispatch::Handle
344              Log::Dispatch::Screen
345              Log::Dispatch::Syslog
346              Log::Dispatch::Tk (by Dominique Dumont)
347
348       Please note that in order to use any of these additional appenders, you
349       have to fetch Log::Dispatch from CPAN and install it. Also the
350       particular appender you're using might require installing the
351       particular module.
352
353       For additional information on appenders, please check the
354       Log::Log4perl::Appender manual page.
355
356   Appender Example
357       Now let's assume that we want to log "info()" or higher prioritized
358       messages in the "Foo::Bar" category to both STDOUT and to a log file,
359       say "test.log".  In the initialization section of your system, just
360       define two appenders using the readily available
361       "Log::Log4perl::Appender::File" and "Log::Log4perl::Appender::Screen"
362       modules:
363
364         use Log::Log4perl;
365
366            # Configuration in a string ...
367         my $conf = q(
368           log4perl.category.Foo.Bar          = INFO, Logfile, Screen
369
370           log4perl.appender.Logfile          = Log::Log4perl::Appender::File
371           log4perl.appender.Logfile.filename = test.log
372           log4perl.appender.Logfile.layout   = Log::Log4perl::Layout::PatternLayout
373           log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n
374
375           log4perl.appender.Screen         = Log::Log4perl::Appender::Screen
376           log4perl.appender.Screen.stderr  = 0
377           log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
378         );
379
380            # ... passed as a reference to init()
381         Log::Log4perl::init( \$conf );
382
383       Once the initialization shown above has happened once, typically in the
384       startup code of your system, just use the defined logger anywhere in
385       your system:
386
387         ##########################
388         # ... in some function ...
389         ##########################
390         my $log = Log::Log4perl::get_logger("Foo::Bar");
391
392           # Logs both to STDOUT and to the file test.log
393         $log->info("Important Info!");
394
395       The "layout" settings specified in the configuration section define the
396       format in which the message is going to be logged by the specified
397       appender. The format shown for the file appender is logging not only
398       the message but also the number of milliseconds since the program has
399       started (%r), the name of the file the call to the logger has happened
400       and the line number there (%F and %L), the message itself (%m) and a
401       OS-specific newline character (%n):
402
403           [187] ./myscript.pl 27 Important Info!
404
405       The screen appender above, on the other hand, uses a "SimpleLayout",
406       which logs the debug level, a hyphen (-) and the log message:
407
408           INFO - Important Info!
409
410       For more detailed info on layout formats, see "Log Layouts".
411
412       In the configuration sample above, we chose to define a category logger
413       ("Foo::Bar").  This will cause only messages originating from this
414       specific category logger to be logged in the defined format and
415       locations.
416
417   Logging newlines
418       There's some controversy between different logging systems as to when
419       and where newlines are supposed to be added to logged messages.
420
421       The Log4perl way is that a logging statement should not contain a
422       newline:
423
424           $logger->info("Some message");
425           $logger->info("Another message");
426
427       If this is supposed to end up in a log file like
428
429           Some message
430           Another message
431
432       then an appropriate appender layout like "%m%n" will take care of
433       adding a newline at the end of each message to make sure every message
434       is printed on its own line.
435
436       Other logging systems, Log::Dispatch in particular, recommend adding
437       the newline to the log statement. This doesn't work well, however, if
438       you, say, replace your file appender by a database appender, and all of
439       a sudden those newlines scattered around the code don't make sense
440       anymore.
441
442       Assigning matching layouts to different appenders and leaving newlines
443       out of the code solves this problem. If you inherited code that has
444       logging statements with newlines and want to make it work with
445       Log4perl, read the Log::Log4perl::Layout::PatternLayout documentation
446       on how to accomplish that.
447
448   Configuration files
449       As shown above, you can define "Log::Log4perl" loggers both from within
450       your Perl code or from configuration files. The latter have the
451       unbeatable advantage that you can modify your system's logging
452       behaviour without interfering with the code at all. So even if your
453       code is being run by somebody who's totally oblivious to Perl, they
454       still can adapt the module's logging behaviour to their needs.
455
456       "Log::Log4perl" has been designed to understand "Log4j" configuration
457       files -- as used by the original Java implementation. Instead of
458       reiterating the format description in [2], let me just list three
459       examples (also derived from [2]), which should also illustrate how it
460       works:
461
462           log4j.rootLogger=DEBUG, A1
463           log4j.appender.A1=org.apache.log4j.ConsoleAppender
464           log4j.appender.A1.layout=org.apache.log4j.PatternLayout
465           log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n
466
467       This enables messages of priority "DEBUG" or higher in the root
468       hierarchy and has the system write them to the console.
469       "ConsoleAppender" is a Java appender, but "Log::Log4perl" jumps through
470       a significant number of hoops internally to map these to their
471       corresponding Perl classes, "Log::Log4perl::Appender::Screen" in this
472       case.
473
474       Second example:
475
476           log4perl.rootLogger=DEBUG, A1
477           log4perl.appender.A1=Log::Log4perl::Appender::Screen
478           log4perl.appender.A1.layout=PatternLayout
479           log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n
480           log4perl.logger.com.foo=WARN
481
482       This defines two loggers: The root logger and the "com.foo" logger.
483       The root logger is easily triggered by debug-messages, but the
484       "com.foo" logger makes sure that messages issued within the "Com::Foo"
485       component and below are only forwarded to the appender if they're of
486       priority warning or higher.
487
488       Note that the "com.foo" logger doesn't define an appender. Therefore,
489       it will just propagate the message up the hierarchy until the root
490       logger picks it up and forwards it to the one and only appender of the
491       root category, using the format defined for it.
492
493       Third example:
494
495           log4j.rootLogger=debug, stdout, R
496           log4j.appender.stdout=org.apache.log4j.ConsoleAppender
497           log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
498           log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n
499           log4j.appender.R=org.apache.log4j.RollingFileAppender
500           log4j.appender.R.File=example.log
501           log4j.appender.R.layout=org.apache.log4j.PatternLayout
502           log4j.appender.R.layout.ConversionPattern=%p %c - %m%n
503
504       The root logger defines two appenders here: "stdout", which uses
505       "org.apache.log4j.ConsoleAppender" (ultimately mapped by
506       "Log::Log4perl" to "Log::Log4perl::Appender::Screen") to write to the
507       screen. And "R", a "org.apache.log4j.RollingFileAppender" (mapped by
508       "Log::Log4perl" to "Log::Dispatch::FileRotate" with the "File"
509       attribute specifying the log file.
510
511       See Log::Log4perl::Config for more examples and syntax explanations.
512
513   Log Layouts
514       If the logging engine passes a message to an appender, because it
515       thinks it should be logged, the appender doesn't just write it out
516       haphazardly. There's ways to tell the appender how to format the
517       message and add all sorts of interesting data to it: The date and time
518       when the event happened, the file, the line number, the debug level of
519       the logger and others.
520
521       There's currently two layouts defined in "Log::Log4perl":
522       "Log::Log4perl::Layout::SimpleLayout" and
523       "Log::Log4perl::Layout::PatternLayout":
524
525       "Log::Log4perl::SimpleLayout"
526           formats a message in a simple way and just prepends it by the debug
527           level and a hyphen: ""$level - $message", for example "FATAL -
528           Can't open password file".
529
530       "Log::Log4perl::Layout::PatternLayout"
531           on the other hand is very powerful and allows for a very flexible
532           format in "printf"-style. The format string can contain a number of
533           placeholders which will be replaced by the logging engine when it's
534           time to log the message:
535
536               %c Category of the logging event.
537               %C Fully qualified package (or class) name of the caller
538               %d Current date in yyyy/MM/dd hh:mm:ss format
539               %F File where the logging event occurred
540               %H Hostname (if Sys::Hostname is available)
541               %l Fully qualified name of the calling method followed by the
542                  callers source the file name and line number between
543                  parentheses.
544               %L Line number within the file where the log statement was issued
545               %m The message to be logged
546               %m{chomp} The message to be logged, stripped off a trailing newline
547               %M Method or function where the logging request was issued
548               %n Newline (OS-independent)
549               %p Priority of the logging event
550               %P pid of the current process
551               %r Number of milliseconds elapsed from program start to logging
552                  event
553               %R Number of milliseconds elapsed from last logging event to
554                  current logging event
555               %T A stack trace of functions called
556               %x The topmost NDC (see below)
557               %X{key} The entry 'key' of the MDC (see below)
558               %% A literal percent (%) sign
559
560           NDC and MDC are explained in "Nested Diagnostic Context (NDC)" and
561           "Mapped Diagnostic Context (MDC)".
562
563           Also, %d can be fine-tuned to display only certain characteristics
564           of a date, according to the SimpleDateFormat in the Java World
565           (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html)
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,
569           followed 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. %c{2}
574           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
587           qualify functions and variables if they're located in different
588           packages.
589
590           SECURITY NOTE: this feature means arbitrary perl code can be
591           embedded in the config file.  In the rare case where the people who
592           have access to your config file are different from the people who
593           write your code and shouldn't have execute rights, you might want
594           to call
595
596               Log::Log4perl::Config->allow_code(0);
597
598           before you call init(). Alternatively you can supply a restricted
599           set of Perl opcodes that can be embedded in the config file as
600           described in "Restricting what Opcodes can be in a Perl Hook".
601
602       All placeholders are quantifiable, just like in printf. Following this
603       tradition, "%-20c" will reserve 20 chars for the category and left-
604       justify it.
605
606       For more details on logging and how to use the flexible and the simple
607       format, check out the original "log4j" website under
608
609           http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/SimpleLayout.html
610           http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
611
612   Penalties
613       Logging comes with a price tag. "Log::Log4perl" has been optimized to
614       allow for maximum performance, both with logging enabled and disabled.
615
616       But you need to be aware that there's a small hit every time your code
617       encounters a log statement -- no matter if logging is enabled or not.
618       "Log::Log4perl" has been designed to keep this so low that it will be
619       unnoticable to most applications.
620
621       Here's a couple of tricks which help "Log::Log4perl" to avoid
622       unnecessary delays:
623
624       You can save serious time if you're logging something like
625
626               # Expensive in non-debug mode!
627           for (@super_long_array) {
628               $logger->debug("Element: $_");
629           }
630
631       and @super_long_array is fairly big, so looping through it is pretty
632       expensive. Only you, the programmer, knows that going through that
633       "for" loop can be skipped entirely if the current logging level for the
634       actual component is higher than "debug".  In this case, use this
635       instead:
636
637               # Cheap in non-debug mode!
638           if($logger->is_debug()) {
639               for (@super_long_array) {
640                   $logger->debug("Element: $_");
641               }
642           }
643
644       If you're afraid that generating the parameters to the logging function
645       is fairly expensive, use closures:
646
647               # Passed as subroutine ref
648           use Data::Dumper;
649           $logger->debug(sub { Dumper($data) } );
650
651       This won't unravel $data via Dumper() unless it's actually needed
652       because it's logged.
653
654       Also, Log::Log4perl lets you specify arguments to logger functions in
655       message output filter syntax:
656
657           $logger->debug("Structure: ",
658                          { filter => \&Dumper,
659                            value  => $someref });
660
661       In this way, shortly before Log::Log4perl sending the message out to
662       any appenders, it will be searching all arguments for hash references
663       and treat them in a special way:
664
665       It will invoke the function given as a reference with the "filter" key
666       ("Data::Dumper::Dumper()") and pass it the value that came with the key
667       named "value" as an argument.  The anonymous hash in the call above
668       will be replaced by the return value of the filter function.
669

Categories

671       Categories are also called "Loggers" in Log4perl, both refer to the the
672       same thing and these terms are used interchangeably.  "Log::Log4perl"
673       uses categories to determine if a log statement in a component should
674       be executed or suppressed at the current logging level.  Most of the
675       time, these categories are just the classes the log statements are
676       located in:
677
678           package Candy::Twix;
679
680           sub new {
681               my $logger = Log::Log4perl->new("Candy::Twix");
682               $logger->debug("Creating a new Twix bar");
683               bless {}, shift;
684           }
685
686           # ...
687
688           package Candy::Snickers;
689
690           sub new {
691               my $logger = Log::Log4perl->new("Candy.Snickers");
692               $logger->debug("Creating a new Snickers bar");
693               bless {}, shift;
694           }
695
696           # ...
697
698           package main;
699           Log::Log4perl->init("mylogdefs.conf");
700
701               # => "LOG> Creating a new Snickers bar"
702           my $first = Candy::Snickers->new();
703               # => "LOG> Creating a new Twix bar"
704           my $second = Candy::Twix->new();
705
706       Note that you can separate your category hierarchy levels using either
707       dots like in Java (.) or double-colons (::) like in Perl. Both
708       notations are equivalent and are handled the same way internally.
709
710       However, categories are just there to make use of inheritance: if you
711       invoke a logger in a sub-category, it will bubble up the hierarchy and
712       call the appropriate appenders.  Internally, categories are not related
713       to the class hierarchy of the program at all -- they're purely virtual.
714       You can use arbitrary categories -- for example in the following
715       program, which isn't oo-style, but procedural:
716
717           sub print_portfolio {
718
719               my $log = Log::Log4perl->new("user.portfolio");
720               $log->debug("Quotes requested: @_");
721
722               for(@_) {
723                   print "$_: ", get_quote($_), "\n";
724               }
725           }
726
727           sub get_quote {
728
729               my $log = Log::Log4perl->new("internet.quotesystem");
730               $log->debug("Fetching quote: $_[0]");
731
732               return yahoo_quote($_[0]);
733           }
734
735       The logger in first function, "print_portfolio", is assigned the
736       (virtual) "user.portfolio" category. Depending on the "Log4perl"
737       configuration, this will either call a "user.portfolio" appender, a
738       "user" appender, or an appender assigned to root -- without
739       "user.portfolio" having any relevance to the class system used in the
740       program.  The logger in the second function adheres to the
741       "internet.quotesystem" category -- again, maybe because it's bundled
742       with other Internet functions, but not because there would be a class
743       of this name somewhere.
744
745       However, be careful, don't go overboard: if you're developing a system
746       in object-oriented style, using the class hierarchy is usually your
747       best choice. Think about the people taking over your code one day: The
748       class hierarchy is probably what they know right up front, so it's easy
749       for them to tune the logging to their needs.
750
751   Turn off a component
752       "Log4perl" doesn't only allow you to selectively switch on a category
753       of log messages, you can also use the mechanism to selectively disable
754       logging in certain components whereas logging is kept turned on in
755       higher-level categories. This mechanism comes in handy if you find that
756       while bumping up the logging level of a high-level (i. e. close to
757       root) category, that one component logs more than it should,
758
759       Here's how it works:
760
761           ############################################################
762           # Turn off logging in a lower-level category while keeping
763           # it active in higher-level categories.
764           ############################################################
765           log4perl.rootLogger=DEBUG, LOGFILE
766           log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE
767
768           # ... Define appenders ...
769
770       This way, log messages issued from within "Deep::Down::The::Hierarchy"
771       and below will be logged only if they're "ERROR" or worse, while in all
772       other system components even "DEBUG" messages will be logged.
773
774   Return Values
775       All logging methods return values indicating if their message actually
776       reached one or more appenders. If the message has been suppressed
777       because of level constraints, "undef" is returned.
778
779       For example,
780
781           my $ret = $logger->info("Message");
782
783       will return "undef" if the system debug level for the current category
784       is not "INFO" or more permissive.  If Log::Log4perl forwarded the
785       message to one or more appenders, the number of appenders is returned.
786
787       If appenders decide to veto on the message with an appender threshold,
788       the log method's return value will have them excluded. This means that
789       if you've got one appender holding an appender threshold and you're
790       logging a message which passes the system's log level hurdle but not
791       the appender threshold, 0 will be returned by the log function.
792
793       The bottom line is: Logging functions will return a true value if the
794       message made it through to one or more appenders and a false value if
795       it didn't.  This allows for constructs like
796
797           $logger->fatal("@_") or print STDERR "@_\n";
798
799       which will ensure that the fatal message isn't lost if the current
800       level is lower than FATAL or printed twice if the level is acceptable
801       but an appender already points to STDERR.
802
803   Pitfalls with Categories
804       Be careful with just blindly reusing the system's packages as
805       categories. If you do, you'll get into trouble with inherited methods.
806       Imagine the following class setup:
807
808           use Log::Log4perl;
809
810           ###########################################
811           package Bar;
812           ###########################################
813           sub new {
814               my($class) = @_;
815               my $logger = Log::Log4perl::get_logger(__PACKAGE__);
816               $logger->debug("Creating instance");
817               bless {}, $class;
818           }
819           ###########################################
820           package Bar::Twix;
821           ###########################################
822           our @ISA = qw(Bar);
823
824           ###########################################
825           package main;
826           ###########################################
827           Log::Log4perl->init(\ qq{
828           log4perl.category.Bar.Twix = DEBUG, Screen
829           log4perl.appender.Screen = Log::Log4perl::Appender::Screen
830           log4perl.appender.Screen.layout = SimpleLayout
831           });
832
833           my $bar = Bar::Twix->new();
834
835       "Bar::Twix" just inherits everything from "Bar", including the
836       constructor "new()".  Contrary to what you might be thinking at first,
837       this won't log anything.  Reason for this is the "get_logger()" call in
838       package "Bar", which will always get a logger of the "Bar" category,
839       even if we call "new()" via the "Bar::Twix" package, which will make
840       perl go up the inheritance tree to actually execute "Bar::new()". Since
841       we've only defined logging behaviour for "Bar::Twix" in the
842       configuration file, nothing will happen.
843
844       This can be fixed by changing the "get_logger()" method in "Bar::new()"
845       to obtain a logger of the category matching the actual class of the
846       object, like in
847
848               # ... in Bar::new() ...
849           my $logger = Log::Log4perl::get_logger($class);
850
851       This way, you'll make sure the logger logs appropriately, no matter if
852       the method is inherited or called directly.  "new()" always gets the
853       real class name as an argument and all other methods can determine it
854       via "ref($self)"), so it shouldn't be a problem to get the right class
855       every time.
856
857   Initialize once and only once
858       It's important to realize that Log::Log4perl gets initialized once and
859       only once, typically at the start of a program or system. Calling
860       "init()" more than once will cause it to clobber the existing
861       configuration and replace it by the new one.
862
863       If you're in a traditional CGI environment, where every request is
864       handeled by a new process, calling "init()" every time is fine. In
865       persistent environments like "mod_perl", however, Log::Log4perl should
866       be initialized either at system startup time (Apache offers startup
867       handlers for that) or via
868
869               # Init or skip if already done
870           Log::Log4perl->init_once($conf_file);
871
872       "init_once()" is identical to "init()", just with the exception that it
873       will leave a potentially existing configuration alone and will only
874       call "init()" if Log::Log4perl hasn't been initialized yet.
875
876       If you're just curious if Log::Log4perl has been initialized yet, the
877       check
878
879           if(Log::Log4perl->initialized()) {
880               # Yes, Log::Log4perl has already been initialized
881           } else {
882               # No, not initialized yet ...
883           }
884
885       can be used.
886
887       If you're afraid that the components of your system are stepping on
888       each other's toes or if you are thinking that different components
889       should initialize Log::Log4perl seperately, try to consolidate your
890       system to use a centralized Log4perl configuration file and use
891       Log4perl's categories to separate your components.
892
893   Custom Filters
894       Log4perl allows the use of customized filters in its appenders to
895       control the output of messages. These filters might grep for certain
896       text chunks in a message, verify that its priority matches or exceeds a
897       certain level or that this is the 10th time the same message has been
898       submitted -- and come to a log/no log decision based upon these
899       circumstantial facts.
900
901       Check out Log::Log4perl::Filter for detailed instructions on how to use
902       them.
903
904   Performance
905       The performance of Log::Log4perl calls obviously depends on a lot of
906       things.  But to give you a general idea, here's some rough numbers:
907
908       On a Pentium 4 Linux box at 2.4 GHz, you'll get through
909
910       ·   500,000 suppressed log statements per second
911
912       ·   30,000 logged messages per second (using an in-memory appender)
913
914       ·   init_and_watch delay mode: 300,000 suppressed, 30,000 logged.
915           init_and_watch signal mode: 450,000 suppressed, 30,000 logged.
916
917       Numbers depend on the complexity of the Log::Log4perl configuration.
918       For a more detailed benchmark test, check the
919       "docs/benchmark.results.txt" document in the Log::Log4perl
920       distribution.
921

Cool Tricks

923       Here's a collection of useful tricks for the advanced "Log::Log4perl"
924       user.  For more, check the the FAQ, either in the distribution
925       (Log::Log4perl::FAQ) or on http://log4perl.sourceforge.net.
926
927   Shortcuts
928       When getting an instance of a logger, instead of saying
929
930           use Log::Log4perl;
931           my $logger = Log::Log4perl->get_logger();
932
933       it's often more convenient to import the "get_logger" method from
934       "Log::Log4perl" into the current namespace:
935
936           use Log::Log4perl qw(get_logger);
937           my $logger = get_logger();
938
939       Please note this difference: To obtain the root logger, please use
940       "get_logger("")", call it without parameters ("get_logger()"), you'll
941       get the logger of a category named after the current package.
942       "get_logger()" is equivalent to "get_logger(__PACKAGE__)".
943
944   Alternative initialization
945       Instead of having "init()" read in a configuration file by specifying a
946       file name or passing it a reference to an open filehandle
947       ("Log::Log4perl->init( \*FILE )"), you can also pass in a reference to
948       a string, containing the content of the file:
949
950           Log::Log4perl->init( \$config_text );
951
952       Also, if you've got the "name=value" pairs of the configuration in a
953       hash, you can just as well initialize "Log::Log4perl" with a reference
954       to it:
955
956           my %key_value_pairs = (
957               "log4perl.rootLogger"       => "ERROR, LOGFILE",
958               "log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File",
959               ...
960           );
961
962           Log::Log4perl->init( \%key_value_pairs );
963
964       Or also you can use a URL, see below:
965
966   Using LWP to parse URLs
967       (This section borrowed from XML::DOM::Parser by T.J. Mather).
968
969       The init() function now also supports URLs, e.g.
970       http://www.erols.com/enno/xsa.xml.  It uses LWP to download the file
971       and then calls parse() on the resulting string.  By default it will use
972       a LWP::UserAgent that is created as follows:
973
974        use LWP::UserAgent;
975        $LWP_USER_AGENT = LWP::UserAgent->new;
976        $LWP_USER_AGENT->env_proxy;
977
978       Note that env_proxy reads proxy settings from environment variables,
979       which is what I need to do to get thru our firewall. If you want to use
980       a different LWP::UserAgent, you can set it with
981
982           Log::Log4perl::Config::set_LWP_UserAgent($my_agent);
983
984       Currently, LWP is used when the filename (passed to parsefile) starts
985       with one of the following URL schemes: http, https, ftp, wais, gopher,
986       or file (followed by a colon.)
987
988       Don't use this feature with init_and_watch().
989
990   Automatic reloading of changed configuration files
991       Instead of just statically initializing Log::Log4perl via
992
993           Log::Log4perl->init($conf_file);
994
995       there's a way to have Log::Log4perl periodically check for changes in
996       the configuration and reload it if necessary:
997
998           Log::Log4perl->init_and_watch($conf_file, $delay);
999
1000       In this mode, Log::Log4perl will examine the configuration file
1001       $conf_file every $delay seconds for changes via the file's last
1002       modification timestamp. If the file has been updated, it will be
1003       reloaded and replace the current Log::Log4perl configuration.
1004
1005       The way this works is that with every logger function called (debug(),
1006       is_debug(), etc.), Log::Log4perl will check if the delay interval has
1007       expired. If so, it will run a -M file check on the configuration file.
1008       If its timestamp has been modified, the current configuration will be
1009       dumped and new content of the file will be loaded.
1010
1011       This convenience comes at a price, though: Calling time() with every
1012       logging function call, especially the ones that are "suppressed" (!),
1013       will slow down these Log4perl calls by about 40%.
1014
1015       To alleviate this performance hit a bit, "init_and_watch()" can be
1016       configured to listen for a Unix signal to reload the configuration
1017       instead:
1018
1019           Log::Log4perl->init_and_watch($conf_file, 'HUP');
1020
1021       This will set up a signal handler for SIGHUP and reload the
1022       configuration if the application receives this signal, e.g. via the
1023       "kill" command:
1024
1025           kill -HUP pid
1026
1027       where "pid" is the process ID of the application. This will bring you
1028       back to about 85% of Log::Log4perl's normal execution speed for
1029       suppressed statements. For details, check out "Performance". For more
1030       info on the signal handler, look for "SIGNAL MODE" in
1031       Log::Log4perl::Config::Watch.
1032
1033       If you have a somewhat long delay set between physical config file
1034       checks or don't want to use the signal associated with the config file
1035       watcher, you can trigger a configuration reload at the next possible
1036       time by calling "Log::Log4perl::Config->watcher->force_next_check()".
1037
1038       One thing to watch out for: If the configuration file contains a syntax
1039       or other fatal error, a running application will stop with "die" if
1040       this damaged configuration will be loaded during runtime, triggered
1041       either by a signal or if the delay period expired and the change is
1042       detected. This behaviour might change in the future.
1043
1044       To allow the application to intercept and control a configuration
1045       reload in init_and_watch mode, a callback can be specified:
1046
1047           Log::Log4perl->init_and_watch($conf_file, 10, {
1048                   preinit_callback => \&callback });
1049
1050       If Log4perl determines that the configuration needs to be reloaded, it
1051       will call the "preinit_callback" function without parameters. If the
1052       callback returns a true value, Log4perl will proceed and reload the
1053       configuration.  If the callback returns a false value, Log4perl will
1054       keep the old configuration and skip reloading it until the next time
1055       around.  Inside the callback, an application can run all kinds of
1056       checks, including accessing the configuration file, which is available
1057       via "Log::Log4perl::Config->watcher()->file()".
1058
1059   Variable Substitution
1060       To avoid having to retype the same expressions over and over again,
1061       Log::Log4perl's configuration files support simple variable
1062       substitution.  New variables are defined simply by adding
1063
1064           varname = value
1065
1066       lines to the configuration file before using
1067
1068           ${varname}
1069
1070       afterwards to recall the assigned values. Here's an example:
1071
1072           layout_class   = Log::Log4perl::Layout::PatternLayout
1073           layout_pattern = %d %F{1} %L> %m %n
1074
1075           log4perl.category.Bar.Twix = WARN, Logfile, Screen
1076
1077           log4perl.appender.Logfile  = Log::Log4perl::Appender::File
1078           log4perl.appender.Logfile.filename = test.log
1079           log4perl.appender.Logfile.layout = ${layout_class}
1080           log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern}
1081
1082           log4perl.appender.Screen  = Log::Log4perl::Appender::Screen
1083           log4perl.appender.Screen.layout = ${layout_class}
1084           log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern}
1085
1086       This is a convenient way to define two appenders with the same layout
1087       without having to retype the pattern definitions.
1088
1089       Variable substitution via "${varname}" will first try to find an
1090       explicitely defined variable. If that fails, it will check your shell's
1091       environment for a variable of that name. If that also fails, the
1092       program will "die()".
1093
1094   Perl Hooks in the Configuration File
1095       If some of the values used in the Log4perl configuration file need to
1096       be dynamically modified by the program, use Perl hooks:
1097
1098           log4perl.appender.File.filename = \
1099               sub { return getLogfileName(); }
1100
1101       Each value starting with the string "sub {..." is interpreted as Perl
1102       code to be executed at the time the application parses the
1103       configuration via "Log::Log4perl::init()". The return value of the
1104       subroutine is used by Log::Log4perl as the configuration value.
1105
1106       The Perl code is executed in the "main" package, functions in other
1107       packages have to be called in fully-qualified notation.
1108
1109       Here's another example, utilizing an environment variable as a username
1110       for a DBI appender:
1111
1112           log4perl.appender.DB.username = \
1113               sub { $ENV{DB_USER_NAME } }
1114
1115       However, please note the difference between these code snippets and
1116       those used for user-defined conversion specifiers as discussed in
1117       Log::Log4perl::Layout::PatternLayout: While the snippets above are run
1118       once when "Log::Log4perl::init()" is called, the conversion specifier
1119       snippets are executed each time a message is rendered according to the
1120       PatternLayout.
1121
1122       SECURITY NOTE: this feature means arbitrary perl code can be embedded
1123       in the config file.  In the rare case where the people who have access
1124       to your config file are different from the people who write your code
1125       and shouldn't have execute rights, you might want to set
1126
1127           Log::Log4perl::Config->allow_code(0);
1128
1129       before you call init().  Alternatively you can supply a restricted set
1130       of Perl opcodes that can be embedded in the config file as described in
1131       "Restricting what Opcodes can be in a Perl Hook".
1132
1133   Restricting what Opcodes can be in a Perl Hook
1134       The value you pass to Log::Log4perl::Config->allow_code() determines
1135       whether the code that is embedded in the config file is eval'd
1136       unrestricted, or eval'd in a Safe compartment.  By default, a value of
1137       '1' is assumed, which does a normal 'eval' without any restrictions. A
1138       value of '0' however prevents any embedded code from being evaluated.
1139
1140       If you would like fine-grained control over what can and cannot be
1141       included in embedded code, then please utilize the following methods:
1142
1143        Log::Log4perl::Config->allow_code( $allow );
1144        Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... );
1145        Log::Log4perl::Config->vars_shared_with_safe_compartment( [ \%vars | $package, \@vars ] );
1146        Log::Log4perl::Config->allowed_code_ops_convenience_map( [ \%map | $name, \@mask ] );
1147
1148       Log::Log4perl::Config->allowed_code_ops() takes a list of opcode masks
1149       that are allowed to run in the compartment.  The opcode masks must be
1150       specified as described in Opcode:
1151
1152        Log::Log4perl::Config->allowed_code_ops(':subprocess');
1153
1154       This example would allow Perl operations like backticks, system, fork,
1155       and waitpid to be executed in the compartment.  Of course, you probably
1156       don't want to use this mask -- it would allow exactly what the Safe
1157       compartment is designed to prevent.
1158
1159       Log::Log4perl::Config->vars_shared_with_safe_compartment() takes the
1160       symbols which should be exported into the Safe compartment before the
1161       code is evaluated.  The keys of this hash are the package names that
1162       the symbols are in, and the values are array references to the literal
1163       symbol names.  For convenience, the default settings export the '%ENV'
1164       hash from the 'main' package into the compartment:
1165
1166        Log::Log4perl::Config->vars_shared_with_safe_compartment(
1167          main => [ '%ENV' ],
1168        );
1169
1170       Log::Log4perl::Config->allowed_code_ops_convenience_map() is an
1171       accessor method to a map of convenience names to opcode masks. At
1172       present, the following convenience names are defined:
1173
1174        safe        = [ ':browse' ]
1175        restrictive = [ ':default' ]
1176
1177       For convenience, if Log::Log4perl::Config->allow_code() is called with
1178       a value which is a key of the map previously defined with
1179       Log::Log4perl::Config->allowed_code_ops_convenience_map(), then the
1180       allowed opcodes are set according to the value defined in the map. If
1181       this is confusing, consider the following:
1182
1183        use Log::Log4perl;
1184
1185        my $config = <<'END';
1186         log4perl.logger = INFO, Main
1187         log4perl.appender.Main = Log::Log4perl::Appender::File
1188         log4perl.appender.Main.filename = \
1189             sub { "example" . getpwuid($<) . ".log" }
1190         log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout
1191        END
1192
1193        $Log::Log4perl::Config->allow_code('restrictive');
1194        Log::Log4perl->init( \$config );       # will fail
1195        $Log::Log4perl::Config->allow_code('safe');
1196        Log::Log4perl->init( \$config );       # will succeed
1197
1198       The reason that the first call to ->init() fails is because the
1199       'restrictive' name maps to an opcode mask of ':default'.  getpwuid() is
1200       not part of ':default', so ->init() fails.  The 'safe' name maps to an
1201       opcode mask of ':browse', which allows getpwuid() to run, so ->init()
1202       succeeds.
1203
1204       allowed_code_ops_convenience_map() can be invoked in several ways:
1205
1206       allowed_code_ops_convenience_map()
1207           Returns the entire convenience name map as a hash reference in
1208           scalar context or a hash in list context.
1209
1210       allowed_code_ops_convenience_map( \%map )
1211           Replaces the entire conveniece name map with the supplied hash
1212           reference.
1213
1214       allowed_code_ops_convenience_map( $name )
1215           Returns the opcode mask for the given convenience name, or undef if
1216           no such name is defined in the map.
1217
1218       allowed_code_ops_convenience_map( $name, \@mask )
1219           Adds the given name/mask pair to the convenience name map.  If the
1220           name already exists in the map, it's value is replaced with the new
1221           mask.
1222
1223       as can vars_shared_with_safe_compartment():
1224
1225       vars_shared_with_safe_compartment()
1226           Return the entire map of packages to variables as a hash reference
1227           in scalar context or a hash in list context.
1228
1229       vars_shared_with_safe_compartment( \%packages )
1230           Replaces the entire map of packages to variables with the supplied
1231           hash reference.
1232
1233       vars_shared_with_safe_compartment( $package )
1234           Returns the arrayref of variables to be shared for a specific
1235           package.
1236
1237       vars_shared_with_safe_compartment( $package, \@vars )
1238           Adds the given package / varlist pair to the map.  If the package
1239           already exists in the map, it's value is replaced with the new
1240           arrayref of variable names.
1241
1242       For more information on opcodes and Safe Compartments, see Opcode and
1243       Safe.
1244
1245   Changing the Log Level on a Logger
1246       Log4perl provides some internal functions for quickly adjusting the log
1247       level from within a running Perl program.
1248
1249       Now, some people might argue that you should adjust your levels from
1250       within an external Log4perl configuration file, but Log4perl is
1251       everybody's darling.
1252
1253       Typically run-time adjusting of levels is done at the beginning, or in
1254       response to some external input (like a "more logging" runtime command
1255       for diagnostics).
1256
1257       You get the log level from a logger object with:
1258
1259           $current_level = $logger->level();
1260
1261       and you may set it with the same method, provided you first imported
1262       the log level constants, with:
1263
1264           use Log::Log4perl::Level;
1265
1266       Then you can set the level on a logger to one of the constants,
1267
1268           $logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL
1269
1270       To increase the level of logging currently being done, use:
1271
1272           $logger->more_logging($delta);
1273
1274       and to decrease it, use:
1275
1276           $logger->less_logging($delta);
1277
1278       $delta must be a positive integer (for now, we may fix this later ;).
1279
1280       There are also two equivalent functions:
1281
1282           $logger->inc_level($delta);
1283           $logger->dec_level($delta);
1284
1285       They're included to allow you a choice in readability. Some folks will
1286       prefer more/less_logging, as they're fairly clear in what they do, and
1287       allow the programmer not to worry too much about what a Level is and
1288       whether a higher Level means more or less logging. However, other folks
1289       who do understand and have lots of code that deals with levels will
1290       probably prefer the inc_level() and dec_level() methods as they want to
1291       work with Levels and not worry about whether that means more or less
1292       logging. :)
1293
1294       That diatribe aside, typically you'll use more_logging() or inc_level()
1295       as such:
1296
1297           my $v = 0; # default level of verbosity.
1298
1299           GetOptions("v+" => \$v, ...);
1300
1301           $logger->more_logging($v);  # inc logging level once for each -v in ARGV
1302
1303   Custom Log Levels
1304       First off, let me tell you that creating custom levels is heavily
1305       deprecated by the log4j folks. Indeed, instead of creating additional
1306       levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL, you
1307       should use categories to control the amount of logging smartly, based
1308       on the location of the log-active code in the system.
1309
1310       Nevertheless, Log4perl provides a nice way to create custom levels via
1311       the create_custom_level() routine function. However, this must be done
1312       before the first call to init() or get_logger(). Say you want to create
1313       a NOTIFY logging level that comes after WARN (and thus before INFO).
1314       You'd do such as follows:
1315
1316           use Log::Log4perl;
1317           use Log::Log4perl::Level;
1318
1319           Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN");
1320
1321       And that's it! create_custom_level() creates the following functions /
1322       variables for level FOO:
1323
1324           $FOO_INT        # integer to use in L4p::Level::to_level()
1325           $logger->foo()  # log function to log if level = FOO
1326           $logger->is_foo()   # true if current level is >= FOO
1327
1328       These levels can also be used in your config file, but note that your
1329       config file probably won't be portable to another log4perl or log4j
1330       environment unless you've made the appropriate mods there too.
1331
1332       Since Log4perl translates log levels to syslog and Log::Dispatch if
1333       their appenders are used, you may add mappings for custom levels as
1334       well:
1335
1336         Log::Log4perl::Level::add_priority("NOTIFY", "WARN",
1337                                            $syslog_equiv, $log_dispatch_level);
1338
1339       For example, if your new custom "NOTIFY" level is supposed to map to
1340       syslog level 2 ("LOG_NOTICE") and Log::Dispatch level 2 ("notice"),
1341       use:
1342
1343         Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN", 2, 2);
1344
1345   System-wide log levels
1346       As a fairly drastic measure to decrease (or increase) the logging level
1347       all over the system with one single configuration option, use the
1348       "threshold" keyword in the Log4perl configuration file:
1349
1350           log4perl.threshold = ERROR
1351
1352       sets the system-wide (or hierarchy-wide according to the log4j
1353       documentation) to ERROR and therefore deprives every logger in the
1354       system of the right to log lower-prio messages.
1355
1356   Easy Mode
1357       For teaching purposes (especially for [1]), I've put ":easy" mode into
1358       "Log::Log4perl", which just initializes a single root logger with a
1359       defined priority and a screen appender including some nice standard
1360       layout:
1361
1362           ### Initialization Section
1363           use Log::Log4perl qw(:easy);
1364           Log::Log4perl->easy_init($ERROR);  # Set priority of root logger to ERROR
1365
1366           ### Application Section
1367           my $logger = get_logger();
1368           $logger->fatal("This will get logged.");
1369           $logger->debug("This won't.");
1370
1371       This will dump something like
1372
1373           2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.
1374
1375       to the screen. While this has been proven to work well familiarizing
1376       people with "Log::Logperl" slowly, effectively avoiding to clobber them
1377       over the head with a plethora of different knobs to fiddle with
1378       (categories, appenders, levels, layout), the overall mission of
1379       "Log::Log4perl" is to let people use categories right from the start to
1380       get used to the concept. So, let's keep this one fairly hidden in the
1381       man page (congrats on reading this far :).
1382
1383   Stealth loggers
1384       Sometimes, people are lazy. If you're whipping up a 50-line script and
1385       want the comfort of Log::Log4perl without having the burden of carrying
1386       a separate log4perl.conf file or a 5-liner defining that you want to
1387       append your log statements to a file, you can use the following
1388       features:
1389
1390           use Log::Log4perl qw(:easy);
1391
1392           Log::Log4perl->easy_init( { level   => $DEBUG,
1393                                       file    => ">>test.log" } );
1394
1395               # Logs to test.log via stealth logger
1396           DEBUG("Debug this!");
1397           INFO("Info this!");
1398           WARN("Warn this!");
1399           ERROR("Error this!");
1400
1401           some_function();
1402
1403           sub some_function {
1404                   # Same here
1405               FATAL("Fatal this!");
1406           }
1407
1408       In ":easy" mode, "Log::Log4perl" will instantiate a stealth logger
1409       named $_default_logger and import it into the current package. Also, it
1410       will introduce the convenience functions "TRACE", "DEBUG()", "INFO()",
1411       "WARN()", "ERROR()", "FATAL()", and "ALWAYS" into the package
1412       namespace.  These functions simply take messages as arguments and
1413       forward them to "_default_logger->debug()", "_default_logger->info()"
1414       and so on.  If a message should never be blocked, regardless of the log
1415       level, use the "ALWAYS" function which corresponds to a log level of
1416       "OFF":
1417
1418           ALWAYS "This will be printed regardless of the log level";
1419
1420       The "easy_init" method can be called with a single level value to
1421       create a STDERR appender and a root logger as in
1422
1423           Log::Log4perl->easy_init($DEBUG);
1424
1425       or, as shown below (and in the example above) with a reference to a
1426       hash, specifying values for "level" (the logger's priority), "file"
1427       (the appender's data sink), "category" (the logger's category> and
1428       "layout" for the appender's pattern layout specification.  All key-
1429       value pairs are optional, they default to $DEBUG for "level", "STDERR"
1430       for "file", "" (root category) for "category" and "%d %m%n" for
1431       "layout":
1432
1433           Log::Log4perl->easy_init( { level    => $DEBUG,
1434                                       file     => ">test.log",
1435                                       utf8     => 1,
1436                                       category => "Bar::Twix",
1437                                       layout   => '%F{1}-%L-%M: %m%n' } );
1438
1439       The "file" parameter takes file names preceded by ">" (overwrite) and
1440       ">>" (append) as arguments. This will cause
1441       "Log::Log4perl::Appender::File" appenders to be created behind the
1442       scenes. Also the keywords "STDOUT" and "STDERR" (no ">" or ">>") are
1443       recognized, which will utilize and configure
1444       "Log::Log4perl::Appender::Screen" appropriately. The "utf8" flag, if
1445       set to a true value, runs a "binmode" command on the file handle to
1446       establish a utf8 line discpline on the file, otherwise you'll get a
1447       'wide character in print' warning message and probably not what you'd
1448       expect as output.
1449
1450       The stealth loggers can be used in different packages, you just need to
1451       make sure you're calling the "use" function in every package you're
1452       using "Log::Log4perl"'s easy services:
1453
1454           package Bar::Twix;
1455           use Log::Log4perl qw(:easy);
1456           sub eat { DEBUG("Twix mjam"); }
1457
1458           package Bar::Mars;
1459           use Log::Log4perl qw(:easy);
1460           sub eat { INFO("Mars mjam"); }
1461
1462           package main;
1463
1464           use Log::Log4perl qw(:easy);
1465
1466           Log::Log4perl->easy_init( { level    => $DEBUG,
1467                                       file     => ">>test.log",
1468                                       category => "Bar::Twix",
1469                                       layout   => '%F{1}-%L-%M: %m%n' },
1470                                     { level    => $DEBUG,
1471                                       file     => "STDOUT",
1472                                       category => "Bar::Mars",
1473                                       layout   => '%m%n' },
1474                                   );
1475           Bar::Twix::eat();
1476           Bar::Mars::eat();
1477
1478       As shown above, "easy_init()" will take any number of different logger
1479       definitions as hash references.
1480
1481       Also, stealth loggers feature the functions "LOGWARN()", "LOGDIE()",
1482       and "LOGEXIT()", combining a logging request with a subsequent Perl
1483       warn() or die() or exit() statement. So, for example
1484
1485           if($all_is_lost) {
1486               LOGDIE("Terrible Problem");
1487           }
1488
1489       will log the message if the package's logger is at least "FATAL" but
1490       "die()" (including the traditional output to STDERR) in any case
1491       afterwards.
1492
1493       See "Log and die or warn" for the similar "logdie()" and "logwarn()"
1494       functions of regular (i.e non-stealth) loggers.
1495
1496       Similarily, "LOGCARP()", "LOGCLUCK()", "LOGCROAK()", and "LOGCONFESS()"
1497       are provided in ":easy" mode, facilitating the use of "logcarp()",
1498       "logcluck()", "logcroak()", and "logconfess()" with stealth loggers.
1499
1500       When using Log::Log4perl in easy mode, please make sure you understand
1501       the implications of "Pitfalls with Categories".
1502
1503       By the way, these convenience functions perform exactly as fast as the
1504       standard Log::Log4perl logger methods, there's no performance penalty
1505       whatsoever.
1506
1507   Nested Diagnostic Context (NDC)
1508       If you find that your application could use a global (thread-specific)
1509       data stack which your loggers throughout the system have easy access
1510       to, use Nested Diagnostic Contexts (NDCs). Also check out "Mapped
1511       Diagnostic Context (MDC)", this might turn out to be even more useful.
1512
1513       For example, when handling a request of a web client, it's probably
1514       useful to have the user's IP address available in all log statements
1515       within code dealing with this particular request. Instead of passing
1516       this piece of data around between your application functions, you can
1517       just use the global (but thread-specific) NDC mechanism. It allows you
1518       to push data pieces (scalars usually) onto its stack via
1519
1520           Log::Log4perl::NDC->push("San");
1521           Log::Log4perl::NDC->push("Francisco");
1522
1523       and have your loggers retrieve them again via the "%x" placeholder in
1524       the PatternLayout. With the stack values above and a PatternLayout
1525       format like "%x %m%n", the call
1526
1527           $logger->debug("rocks");
1528
1529       will end up as
1530
1531           San Francisco rocks
1532
1533       in the log appender.
1534
1535       The stack mechanism allows for nested structures.  Just make sure that
1536       at the end of the request, you either decrease the stack one by one by
1537       calling
1538
1539           Log::Log4perl::NDC->pop();
1540           Log::Log4perl::NDC->pop();
1541
1542       or clear out the entire NDC stack by calling
1543
1544           Log::Log4perl::NDC->remove();
1545
1546       Even if you should forget to do that, "Log::Log4perl" won't grow the
1547       stack indefinitely, but limit it to a maximum, defined in
1548       "Log::Log4perl::NDC" (currently 5). A call to "push()" on a full stack
1549       will just replace the topmost element by the new value.
1550
1551       Again, the stack is always available via the "%x" placeholder in the
1552       Log::Log4perl::Layout::PatternLayout class whenever a logger fires. It
1553       will replace "%x" by the blank-separated list of the values on the
1554       stack. It does that by just calling
1555
1556           Log::Log4perl::NDC->get();
1557
1558       internally. See details on how this standard log4j feature is
1559       implemented in Log::Log4perl::NDC.
1560
1561   Mapped Diagnostic Context (MDC)
1562       Just like the previously discussed NDC stores thread-specific
1563       information in a stack structure, the MDC implements a hash table to
1564       store key/value pairs in.
1565
1566       The static method
1567
1568           Log::Log4perl::MDC->put($key, $value);
1569
1570       stores $value under a key $key, with which it can be retrieved later
1571       (possibly in a totally different part of the system) by calling the
1572       "get" method:
1573
1574           my $value = Log::Log4perl::MDC->get($key);
1575
1576       If no value has been stored previously under $key, the "get" method
1577       will return "undef".
1578
1579       Typically, MDC values are retrieved later on via the "%X{...}"
1580       placeholder in "Log::Log4perl::Layout::PatternLayout". If the "get()"
1581       method returns "undef", the placeholder will expand to the string
1582       "[undef]".
1583
1584       An application taking a web request might store the remote host like
1585
1586           Log::Log4perl::MDC->put("remote_host", $r->headers("HOST"));
1587
1588       at its beginning and if the appender's layout looks something like
1589
1590           log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n
1591
1592       then a log statement like
1593
1594          DEBUG("Content delivered");
1595
1596       will log something like
1597
1598          adsl-63.dsl.snf.pacbell.net: Content delivered
1599
1600       later on in the program.
1601
1602       For details, please check Log::Log4perl::MDC.
1603
1604   Resurrecting hidden Log4perl Statements
1605       Sometimes scripts need to be deployed in environments without having
1606       Log::Log4perl installed yet. On the other hand, you dont't want to live
1607       without your Log4perl statements -- they're gonna come in handy later.
1608
1609       So, just deploy your script with Log4perl statements commented out with
1610       the pattern "###l4p", like in
1611
1612           ###l4p DEBUG "It works!";
1613           # ...
1614           ###l4p INFO "Really!";
1615
1616       If Log::Log4perl is available, use the ":resurrect" tag to have
1617       Log4perl resurrect those burried statements before the script starts
1618       running:
1619
1620           use Log::Log4perl qw(:resurrect :easy);
1621
1622           ###l4p Log::Log4perl->easy_init($DEBUG);
1623           ###l4p DEBUG "It works!";
1624           # ...
1625           ###l4p INFO "Really!";
1626
1627       This will have a source filter kick in and indeed print
1628
1629           2004/11/18 22:08:46 It works!
1630           2004/11/18 22:08:46 Really!
1631
1632       In environments lacking Log::Log4perl, just comment out the first line
1633       and the script will run nevertheless (but of course without logging):
1634
1635           # use Log::Log4perl qw(:resurrect :easy);
1636
1637           ###l4p Log::Log4perl->easy_init($DEBUG);
1638           ###l4p DEBUG "It works!";
1639           # ...
1640           ###l4p INFO "Really!";
1641
1642       because everything's a regular comment now. Alternatively, put the
1643       magic Log::Log4perl comment resurrection line into your shell's
1644       PERL5OPT environment variable, e.g. for bash:
1645
1646           set PERL5OPT=-MLog::Log4perl=:resurrect,:easy
1647           export PERL5OPT
1648
1649       This will awaken the giant within an otherwise silent script like the
1650       following:
1651
1652           #!/usr/bin/perl
1653
1654           ###l4p Log::Log4perl->easy_init($DEBUG);
1655           ###l4p DEBUG "It works!";
1656
1657       As of "Log::Log4perl" 1.12, you can even force all modules loaded by a
1658       script to have their hidden Log4perl statements resurrected. For this
1659       to happen, load "Log::Log4perl::Resurrector" before loading any
1660       modules:
1661
1662           use Log::Log4perl qw(:easy);
1663           use Log::Log4perl::Resurrector;
1664
1665           use Foobar; # All hidden Log4perl statements in here will
1666                       # be uncommented before Foobar gets loaded.
1667
1668           Log::Log4perl->easy_init($DEBUG);
1669           ...
1670
1671       Check the "Log::Log4perl::Resurrector" manpage for more details.
1672
1673   Access defined appenders
1674       All appenders defined in the configuration file or via Perl code can be
1675       retrieved by the "appender_by_name()" class method. This comes in handy
1676       if you want to manipulate or query appender properties after the
1677       Log4perl configuration has been loaded via "init()".
1678
1679       Note that internally, Log::Log4perl uses the "Log::Log4perl::Appender"
1680       wrapper class to control the real appenders (like
1681       "Log::Log4perl::Appender::File" or "Log::Dispatch::FileRotate").  The
1682       "Log::Log4perl::Appender" class has an "appender" attribute, pointing
1683       to the real appender.
1684
1685       The reason for this is that external appenders like
1686       "Log::Dispatch::FileRotate" don't support all of Log::Log4perl's
1687       appender control mechanisms (like appender thresholds).
1688
1689       The previously mentioned method "appender_by_name()" returns a
1690       reference to the real appender object. If you want access to the
1691       wrapper class (e.g. if you want to modify the appender's threshold),
1692       use the hash $Log::Log4perl::Logger::APPENDER_BY_NAME{...} instead,
1693       which holds references to all appender wrapper objects.
1694
1695   Modify appender thresholds
1696       To conveniently adjust appender thresholds (e.g. because a script uses
1697       more_logging()), use
1698
1699              # decrease thresholds of all appenders
1700           Log::Log4perl->appender_thresholds_adjust(-1);
1701
1702       This will decrease the thresholds of all appenders in the system by one
1703       level, i.e. WARN becomes INFO, INFO becomes DEBUG, etc. To only modify
1704       selected ones, use
1705
1706              # decrease thresholds of all appenders
1707           Log::Log4perl->appender_thresholds_adjust(-1, ['AppName1', ...]);
1708
1709       and pass the names of affected appenders in a ref to an array.
1710

Advanced configuration within Perl

1712       Initializing Log::Log4perl can certainly also be done from within Perl.
1713       At last, this is what "Log::Log4perl::Config" does behind the scenes.
1714       Log::Log4perl's configuration file parsers are using a publically
1715       available API to set up Log::Log4perl's categories, appenders and
1716       layouts.
1717
1718       Here's an example on how to configure two appenders with the same
1719       layout in Perl, without using a configuration file at all:
1720
1721         ########################
1722         # Initialization section
1723         ########################
1724         use Log::Log4perl;
1725         use Log::Log4perl::Layout;
1726         use Log::Log4perl::Level;
1727
1728            # Define a category logger
1729         my $log = Log::Log4perl->get_logger("Foo::Bar");
1730
1731            # Define a layout
1732         my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
1733
1734            # Define a file appender
1735         my $file_appender = Log::Log4perl::Appender->new(
1736                                 "Log::Log4perl::Appender::File",
1737                                 name      => "filelog",
1738                                 filename  => "/tmp/my.log");
1739
1740            # Define a stdout appender
1741         my $stdout_appender =  Log::Log4perl::Appender->new(
1742                                 "Log::Log4perl::Appender::Screen",
1743                                 name      => "screenlog",
1744                                 stderr    => 0);
1745
1746            # Have both appenders use the same layout (could be different)
1747         $stdout_appender->layout($layout);
1748         $file_appender->layout($layout);
1749
1750         $log->add_appender($stdout_appender);
1751         $log->add_appender($file_appender);
1752         $log->level($INFO);
1753
1754       Please note the class of the appender object is passed as a string to
1755       "Log::Log4perl::Appender" in the first argument. Behind the scenes,
1756       "Log::Log4perl::Appender" will create the necessary
1757       "Log::Log4perl::Appender::*" (or "Log::Dispatch::*") object and pass
1758       along the name value pairs we provided to
1759       "Log::Log4perl::Appender->new()" after the first argument.
1760
1761       The "name" value is optional and if you don't provide one,
1762       "Log::Log4perl::Appender->new()" will create a unique one for you.  The
1763       names and values of additional parameters are dependent on the
1764       requirements of the particular appender class and can be looked up in
1765       their manual pages.
1766
1767       A side note: In case you're wondering if
1768       "Log::Log4perl::Appender->new()" will also take care of the "min_level"
1769       argument to the "Log::Dispatch::*" constructors called behind the
1770       scenes -- yes, it does. This is because we want the "Log::Dispatch"
1771       objects to blindly log everything we send them ("debug" is their lowest
1772       setting) because we in "Log::Log4perl" want to call the shots and
1773       decide on when and what to log.
1774
1775       The call to the appender's layout() method specifies the format (as a
1776       previously created "Log::Log4perl::Layout::PatternLayout" object) in
1777       which the message is being logged in the specified appender.  If you
1778       don't specify a layout, the logger will fall back to
1779       "Log::Log4perl::SimpleLayout", which logs the debug level, a hyphen (-)
1780       and the log message.
1781
1782       Layouts are objects, here's how you create them:
1783
1784               # Create a simple layout
1785           my $simple = Log::Log4perl::SimpleLayout();
1786
1787               # create a flexible layout:
1788               # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\n")
1789           my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n");
1790
1791       Every appender has exactly one layout assigned to it. You assign the
1792       layout to the appender using the appender's "layout()" object:
1793
1794           my $app =  Log::Log4perl::Appender->new(
1795                         "Log::Log4perl::Appender::Screen",
1796                         name      => "screenlog",
1797                         stderr    => 0);
1798
1799               # Assign the previously defined flexible layout
1800           $app->layout($pattern);
1801
1802               # Add the appender to a previously defined logger
1803           $logger->add_appender($app);
1804
1805               # ... and you're good to go!
1806           $logger->debug("Blah");
1807               # => "2002/07/10 23:55:35 (test.pl:207)> Blah\n"
1808
1809       It's also possible to remove appenders from a logger:
1810
1811           $logger->remove_appender($appender_name);
1812
1813       will remove an appender, specified by name, from a given logger.
1814       Please note that this does not remove an appender from the system.
1815
1816       To eradicate an appender from the system, you need to call
1817       "Log::Log4perl->eradicate_appender($appender_name)" which will first
1818       remove the appender from every logger in the system and then will
1819       delete all references Log4perl holds to it.
1820

How about Log::Dispatch::Config?

1822       Tatsuhiko Miyagawa's "Log::Dispatch::Config" is a very clever
1823       simplified logger implementation, covering some of the log4j
1824       functionality. Among the things that "Log::Log4perl" can but
1825       "Log::Dispatch::Config" can't are:
1826
1827       ·   You can't assign categories to loggers. For small systems that's
1828           fine, but if you can't turn off and on detailed logging in only a
1829           tiny subsystem of your environment, you're missing out on a majorly
1830           useful log4j feature.
1831
1832       ·   Defining appender thresholds. Important if you want to solve
1833           problems like "log all messages of level FATAL to STDERR, plus log
1834           all DEBUG messages in "Foo::Bar" to a log file". If you don't have
1835           appenders thresholds, there's no way to prevent cluttering STDERR
1836           with DEBUG messages.
1837
1838       ·   PatternLayout specifications in accordance with the standard (e.g.
1839           "%d{HH:mm}").
1840
1841       Bottom line: Log::Dispatch::Config is fine for small systems with
1842       simple logging requirements. However, if you're designing a system with
1843       lots of subsystems which you need to control independantly, you'll love
1844       the features of "Log::Log4perl", which is equally easy to use.
1845

Using Log::Log4perl with wrapper functions and classes

1847       If you don't use "Log::Log4perl" as described above, but from a wrapper
1848       function, the pattern layout will generate wrong data for %F, %C, %L,
1849       and the like. Reason for this is that "Log::Log4perl"'s loggers assume
1850       a static caller depth to the application that's using them.
1851
1852       If you're using one (or more) wrapper functions, "Log::Log4perl" will
1853       indicate where your logger function called the loggers, not where your
1854       application called your wrapper:
1855
1856           use Log::Log4perl qw(:easy);
1857           Log::Log4perl->easy_init({ level => $DEBUG,
1858                                      layout => "%M %m%n" });
1859
1860           sub mylog {
1861               my($message) = @_;
1862
1863               DEBUG $message;
1864           }
1865
1866           sub func {
1867               mylog "Hello";
1868           }
1869
1870           func();
1871
1872       prints
1873
1874           main::mylog Hello
1875
1876       but that's probably not what your application expects. Rather, you'd
1877       want
1878
1879           main::func Hello
1880
1881       because the "func" function called your logging function.
1882
1883       But don't dispair, there's a solution: Just register your wrapper
1884       package with Log4perl beforehand. If Log4perl then finds that it's
1885       being called from a registered wrapper, it will automatically step up
1886       to the next call frame.
1887
1888           Log::Log4perl->wrapper_register(__PACKAGE__);
1889
1890           sub mylog {
1891               my($message) = @_;
1892
1893               DEBUG $message;
1894           }
1895
1896       Alternatively, you can increase the value of the global variable
1897       $Log::Log4perl::caller_depth (defaults to 0) by one for every wrapper
1898       that's in between your application and "Log::Log4perl", then
1899       "Log::Log4perl" will compensate for the difference:
1900
1901           sub mylog {
1902               my($message) = @_;
1903
1904               local $Log::Log4perl::caller_depth =
1905                     $Log::Log4perl::caller_depth + 1;
1906               DEBUG $message;
1907           }
1908
1909       Also, note that if you're writing a subclass of Log4perl, like
1910
1911           package MyL4pWrapper;
1912           use Log::Log4perl;
1913           our @ISA = qw(Log::Log4perl);
1914
1915       and you want to call get_logger() in your code, like
1916
1917           use MyL4pWrapper;
1918
1919           sub get_logger {
1920               my $logger = Log::Log4perl->get_logger();
1921           }
1922
1923       then the get_logger() call will get a logger for the "MyL4pWrapper"
1924       category, not for the package calling the wrapper class as in
1925
1926           package UserPackage;
1927           my $logger = MyL4pWrapper->get_logger();
1928
1929       To have the above call to get_logger return a logger for the
1930       "UserPackage" category, you need to tell Log4perl that "MyL4pWrapper"
1931       is a Log4perl wrapper class:
1932
1933           use MyL4pWrapper;
1934           Log::Log4perl->wrapper_register(__PACKAGE__);
1935
1936           sub get_logger {
1937                 # Now gets a logger for the category of the calling package
1938               my $logger = Log::Log4perl->get_logger();
1939           }
1940
1941       This feature works both for Log4perl-relaying classes like the wrapper
1942       described above, and for wrappers that inherit from Log4perl use
1943       Log4perl's get_logger function via inheritance, alike.
1944

Access to Internals

1946       The following methods are only of use if you want to peek/poke in the
1947       internals of Log::Log4perl. Be careful not to disrupt its inner
1948       workings.
1949
1950       "Log::Log4perl->appenders()"
1951           To find out which appenders are currently defined (not only for a
1952           particular logger, but overall), a "appenders()" method is
1953           available to return a reference to a hash mapping appender names to
1954           their Log::Log4perl::Appender object references.
1955

Dirty Tricks

1957       infiltrate_lwp()
1958           The famous LWP::UserAgent module isn't Log::Log4perl-enabled.
1959           Often, though, especially when tracing Web-related problems, it
1960           would be helpful to get some insight on what's happening inside
1961           LWP::UserAgent. Ideally, LWP::UserAgent would even play along in
1962           the Log::Log4perl framework.
1963
1964           A call to "Log::Log4perl->infiltrate_lwp()" does exactly this.  In
1965           a very rude way, it pulls the rug from under LWP::UserAgent and
1966           transforms its "debug/conn" messages into "debug()" calls of
1967           loggers of the category "LWP::UserAgent". Similarily,
1968           "LWP::UserAgent"'s "trace" messages are turned into
1969           "Log::Log4perl"'s "info()" method calls. Note that this only works
1970           for LWP::UserAgent versions < 5.822, because this (and probably
1971           later) versions miss debugging functions entirely.
1972
1973       Suppressing 'duplicate' LOGDIE messages
1974           If a script with a simple Log4perl configuration uses logdie() to
1975           catch errors and stop processing, as in
1976
1977               use Log::Log4perl qw(:easy) ;
1978               Log::Log4perl->easy_init($DEBUG);
1979
1980               shaky_function() or LOGDIE "It failed!";
1981
1982           there's a cosmetic problem: The message gets printed twice:
1983
1984               2005/07/10 18:37:14 It failed!
1985               It failed! at ./t line 12
1986
1987           The obvious solution is to use LOGEXIT() instead of LOGDIE(), but
1988           there's also a special tag for Log4perl that suppresses the second
1989           message:
1990
1991               use Log::Log4perl qw(:no_extra_logdie_message);
1992
1993           This causes logdie() and logcroak() to call exit() instead of
1994           die(). To modify the script exit code in these occasions, set the
1995           variable $Log::Log4perl::LOGEXIT_CODE to the desired value, the
1996           default is 1.
1997
1998       Redefine values without causing errors
1999           Log4perl's configuration file parser has a few basic safety
2000           mechanisms to make sure configurations are more or less sane.
2001
2002           One of these safety measures is catching redefined values. For
2003           example, if you first write
2004
2005               log4perl.category = WARN, Logfile
2006
2007           and then a couple of lines later
2008
2009               log4perl.category = TRACE, Logfile
2010
2011           then you might have unintentionally overwritten the first value and
2012           Log4perl will die on this with an error (suspicious configurations
2013           always throw an error). Now, there's a chance that this is
2014           intentional, for example when you're lumping together several
2015           configuration files and actually want the first value to overwrite
2016           the second. In this case use
2017
2018               use Log::Log4perl qw(:nostrict);
2019
2020           to put Log4perl in a more permissive mode.
2021

EXAMPLE

2023       A simple example to cut-and-paste and get started:
2024
2025           use Log::Log4perl qw(get_logger);
2026
2027           my $conf = q(
2028           log4perl.category.Bar.Twix         = WARN, Logfile
2029           log4perl.appender.Logfile          = Log::Log4perl::Appender::File
2030           log4perl.appender.Logfile.filename = test.log
2031           log4perl.appender.Logfile.layout = \
2032               Log::Log4perl::Layout::PatternLayout
2033           log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
2034           );
2035
2036           Log::Log4perl::init(\$conf);
2037
2038           my $logger = get_logger("Bar::Twix");
2039           $logger->error("Blah");
2040
2041       This will log something like
2042
2043           2002/09/19 23:48:15 t1 25> Blah
2044
2045       to the log file "test.log", which Log4perl will append to or create it
2046       if it doesn't exist already.
2047

INSTALLATION

2049       If you want to use external appenders provided with "Log::Dispatch",
2050       you need to install "Log::Dispatch" (2.00 or better) from CPAN, which
2051       itself depends on "Attribute-Handlers" and "Params-Validate". And a lot
2052       of other modules, that's the reason why we're now shipping
2053       Log::Log4perl with its own standard appenders and only if you wish to
2054       use additional ones, you'll have to go through the "Log::Dispatch"
2055       installation process.
2056
2057       Log::Log4perl needs "Test::More", "Test::Harness" and "File::Spec", but
2058       they already come with fairly recent versions of perl.  If not,
2059       everything's automatically fetched from CPAN if you're using the CPAN
2060       shell (CPAN.pm), because they're listed as dependencies.
2061
2062       "Time::HiRes" (1.20 or better) is required only if you need the fine-
2063       grained time stamps of the %r parameter in
2064       "Log::Log4perl::Layout::PatternLayout".
2065
2066       Manual installation works as usual with
2067
2068           perl Makefile.PL
2069           make
2070           make test
2071           make install
2072
2073       If you're running Windows (98, 2000, NT, XP etc.), and you're too lazy
2074       to rummage through all of Log-Log4perl's dependencies, don't despair:
2075       We're providing a PPM package which installs easily with your
2076       Activestate Perl. Check
2077       "how_can_i_install_log__log4perl_on_microsoft_windows" in
2078       Log::Log4perl::FAQ for details.
2079

DEVELOPMENT

2081       Log::Log4perl is still being actively developed. We will always make
2082       sure the test suite (approx. 500 cases) will pass, but there might
2083       still be bugs. please check http://github.com/mschilli/log4perl for the
2084       latest release. The api has reached a mature state, we will not change
2085       it unless for a good reason.
2086
2087       Bug reports and feedback are always welcome, just email them to our
2088       mailing list shown in the AUTHORS section. We're usually addressing
2089       them immediately.
2090

REFERENCES

2092       [1] Michael Schilli, "Retire your debugger, log smartly with
2093           Log::Log4perl!", Tutorial on perl.com, 09/2002,
2094           http://www.perl.com/pub/a/2002/09/11/log4perl.html
2095
2096       [2] Ceki GA~XlcA~X, "Short introduction to log4j",
2097           http://jakarta.apache.org/log4j/docs/manual.html
2098
2099       [3] Vipan Singla, "Don't Use System.out.println! Use Log4j.",
2100           http://www.vipan.com/htdocs/log4jhelp.html
2101
2102       [4] The Log::Log4perl project home page: http://log4perl.com
2103

SEE ALSO

2105       Log::Log4perl::Config, Log::Log4perl::Appender,
2106       Log::Log4perl::Layout::PatternLayout,
2107       Log::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level,
2108       Log::Log4perl::JavaMap Log::Log4perl::NDC,
2109

AUTHORS

2111       Please contribute patches to the project page on Github:
2112
2113           http://github.com/mschilli/log4perl
2114
2115       Bug reports or requests for enhancements to the authors via our
2116
2117           MAILING LIST (questions, bug reports, suggestions/patches):
2118           log4perl-devel@lists.sourceforge.net
2119
2120           Authors (please contact them via the list above, not directly)
2121           Mike Schilli <m@perlmeister.com>
2122           Kevin Goess <cpan@goess.org>
2123
2124           Contributors (in alphabetical order):
2125           Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
2126           Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
2127           Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
2128           Grundman, Paul Harrington, David Hull, Robert Jacobson, Jason Kohles,
2129           Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik
2130           Selberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang.
2131
2133       Copyright 2002-2009 by Mike Schilli <m@perlmeister.com> and Kevin Goess
2134       <cpan@goess.org>.
2135
2136       This library is free software; you can redistribute it and/or modify it
2137       under the same terms as Perl itself.
2138
2139
2140
2141perl v5.12.2                      2010-08-31                  Log::Log4perl(3)
Impressum