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

Categories

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

Cool Tricks

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

Advanced configuration within Perl

1753       Initializing Log::Log4perl can certainly also be done from within Perl.
1754       At last, this is what "Log::Log4perl::Config" does behind the scenes.
1755       Log::Log4perl's configuration file parsers are using a publically
1756       available API to set up Log::Log4perl's categories, appenders and
1757       layouts.
1758
1759       Here's an example on how to configure two appenders with the same
1760       layout in Perl, without using a configuration file at all:
1761
1762         ########################
1763         # Initialization section
1764         ########################
1765         use Log::Log4perl;
1766         use Log::Log4perl::Layout;
1767         use Log::Log4perl::Level;
1768
1769            # Define a category logger
1770         my $log = Log::Log4perl->get_logger("Foo::Bar");
1771
1772            # Define a layout
1773         my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
1774
1775            # Define a file appender
1776         my $file_appender = Log::Log4perl::Appender->new(
1777                                 "Log::Log4perl::Appender::File",
1778                                 name      => "filelog",
1779                                 filename  => "/tmp/my.log");
1780
1781            # Define a stdout appender
1782         my $stdout_appender =  Log::Log4perl::Appender->new(
1783                                 "Log::Log4perl::Appender::Screen",
1784                                 name      => "screenlog",
1785                                 stderr    => 0);
1786
1787            # Define a mixed stderr/stdout appender
1788         my $mixed_stdout_stderr_appender = Log::Log4perl::Appender->new(
1789                                 "Log::Log4perl::Appender::Screen",
1790                                 name      => "screenlog",
1791                                 stderr    => { ERROR => 1, FATAL => 1 });
1792
1793            # Have both appenders use the same layout (could be different)
1794         $stdout_appender->layout($layout);
1795         $file_appender->layout($layout);
1796
1797         $log->add_appender($stdout_appender);
1798         $log->add_appender($file_appender);
1799         $log->level($INFO);
1800
1801       Please note the class of the appender object is passed as a string to
1802       "Log::Log4perl::Appender" in the first argument. Behind the scenes,
1803       "Log::Log4perl::Appender" will create the necessary
1804       "Log::Log4perl::Appender::*" (or "Log::Dispatch::*") object and pass
1805       along the name value pairs we provided to
1806       "Log::Log4perl::Appender->new()" after the first argument.
1807
1808       The "name" value is optional and if you don't provide one,
1809       "Log::Log4perl::Appender->new()" will create a unique one for you.  The
1810       names and values of additional parameters are dependent on the
1811       requirements of the particular appender class and can be looked up in
1812       their manual pages.
1813
1814       A side note: In case you're wondering if
1815       "Log::Log4perl::Appender->new()" will also take care of the "min_level"
1816       argument to the "Log::Dispatch::*" constructors called behind the
1817       scenes -- yes, it does. This is because we want the "Log::Dispatch"
1818       objects to blindly log everything we send them ("debug" is their lowest
1819       setting) because we in "Log::Log4perl" want to call the shots and
1820       decide on when and what to log.
1821
1822       The call to the appender's layout() method specifies the format (as a
1823       previously created "Log::Log4perl::Layout::PatternLayout" object) in
1824       which the message is being logged in the specified appender.  If you
1825       don't specify a layout, the logger will fall back to
1826       "Log::Log4perl::SimpleLayout", which logs the debug level, a hyphen (-)
1827       and the log message.
1828
1829       Layouts are objects, here's how you create them:
1830
1831               # Create a simple layout
1832           my $simple = Log::Log4perl::SimpleLayout();
1833
1834               # create a flexible layout:
1835               # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\n")
1836           my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n");
1837
1838       Every appender has exactly one layout assigned to it. You assign the
1839       layout to the appender using the appender's layout() object:
1840
1841           my $app =  Log::Log4perl::Appender->new(
1842                         "Log::Log4perl::Appender::Screen",
1843                         name      => "screenlog",
1844                         stderr    => 0);
1845
1846               # Assign the previously defined flexible layout
1847           $app->layout($pattern);
1848
1849               # Add the appender to a previously defined logger
1850           $logger->add_appender($app);
1851
1852               # ... and you're good to go!
1853           $logger->debug("Blah");
1854               # => "2002/07/10 23:55:35 (test.pl:207)> Blah\n"
1855
1856       It's also possible to remove appenders from a logger:
1857
1858           $logger->remove_appender($appender_name);
1859
1860       will remove an appender, specified by name, from a given logger.
1861       Please note that this does not remove an appender from the system.
1862
1863       To eradicate an appender from the system, you need to call
1864       "Log::Log4perl->eradicate_appender($appender_name)" which will first
1865       remove the appender from every logger in the system and then will
1866       delete all references Log4perl holds to it.
1867
1868       To remove a logger from the system, use
1869       "Log::Log4perl->remove_logger($logger)". After the remaining reference
1870       $logger goes away, the logger will self-destruct. If the logger in
1871       question is a stealth logger, all of its convenience shortcuts (DEBUG,
1872       INFO, etc) will turn into no-ops.
1873

How about Log::Dispatch::Config?

1875       Tatsuhiko Miyagawa's "Log::Dispatch::Config" is a very clever
1876       simplified logger implementation, covering some of the log4j
1877       functionality. Among the things that "Log::Log4perl" can but
1878       "Log::Dispatch::Config" can't are:
1879
1880       •   You can't assign categories to loggers. For small systems that's
1881           fine, but if you can't turn off and on detailed logging in only a
1882           tiny subsystem of your environment, you're missing out on a majorly
1883           useful log4j feature.
1884
1885       •   Defining appender thresholds. Important if you want to solve
1886           problems like "log all messages of level FATAL to STDERR, plus log
1887           all DEBUG messages in "Foo::Bar" to a log file". If you don't have
1888           appenders thresholds, there's no way to prevent cluttering STDERR
1889           with DEBUG messages.
1890
1891       •   PatternLayout specifications in accordance with the standard (e.g.
1892           "%d{HH:mm}").
1893
1894       Bottom line: Log::Dispatch::Config is fine for small systems with
1895       simple logging requirements. However, if you're designing a system with
1896       lots of subsystems which you need to control independently, you'll love
1897       the features of "Log::Log4perl", which is equally easy to use.
1898

Using Log::Log4perl with wrapper functions and classes

1900       If you don't use "Log::Log4perl" as described above, but from a wrapper
1901       function, the pattern layout will generate wrong data for %F, %C, %L,
1902       and the like. Reason for this is that "Log::Log4perl"'s loggers assume
1903       a static caller depth to the application that's using them.
1904
1905       If you're using one (or more) wrapper functions, "Log::Log4perl" will
1906       indicate where your logger function called the loggers, not where your
1907       application called your wrapper:
1908
1909           use Log::Log4perl qw(:easy);
1910           Log::Log4perl->easy_init({ level => $DEBUG,
1911                                      layout => "%M %m%n" });
1912
1913           sub mylog {
1914               my($message) = @_;
1915
1916               DEBUG $message;
1917           }
1918
1919           sub func {
1920               mylog "Hello";
1921           }
1922
1923           func();
1924
1925       prints
1926
1927           main::mylog Hello
1928
1929       but that's probably not what your application expects. Rather, you'd
1930       want
1931
1932           main::func Hello
1933
1934       because the "func" function called your logging function.
1935
1936       But don't despair, there's a solution: Just register your wrapper
1937       package with Log4perl beforehand. If Log4perl then finds that it's
1938       being called from a registered wrapper, it will automatically step up
1939       to the next call frame.
1940
1941           Log::Log4perl->wrapper_register(__PACKAGE__);
1942
1943           sub mylog {
1944               my($message) = @_;
1945
1946               DEBUG $message;
1947           }
1948
1949       Alternatively, you can increase the value of the global variable
1950       $Log::Log4perl::caller_depth (defaults to 0) by one for every wrapper
1951       that's in between your application and "Log::Log4perl", then
1952       "Log::Log4perl" will compensate for the difference:
1953
1954           sub mylog {
1955               my($message) = @_;
1956
1957               local $Log::Log4perl::caller_depth =
1958                     $Log::Log4perl::caller_depth + 1;
1959               DEBUG $message;
1960           }
1961
1962       Also, note that if you're writing a subclass of Log4perl, like
1963
1964           package MyL4pWrapper;
1965           use Log::Log4perl;
1966           our @ISA = qw(Log::Log4perl);
1967
1968       and you want to call get_logger() in your code, like
1969
1970           use MyL4pWrapper;
1971
1972           sub get_logger {
1973               my $logger = Log::Log4perl->get_logger();
1974           }
1975
1976       then the get_logger() call will get a logger for the "MyL4pWrapper"
1977       category, not for the package calling the wrapper class as in
1978
1979           package UserPackage;
1980           my $logger = MyL4pWrapper->get_logger();
1981
1982       To have the above call to get_logger return a logger for the
1983       "UserPackage" category, you need to tell Log4perl that "MyL4pWrapper"
1984       is a Log4perl wrapper class:
1985
1986           use MyL4pWrapper;
1987           Log::Log4perl->wrapper_register(__PACKAGE__);
1988
1989           sub get_logger {
1990                 # Now gets a logger for the category of the calling package
1991               my $logger = Log::Log4perl->get_logger();
1992           }
1993
1994       This feature works both for Log4perl-relaying classes like the wrapper
1995       described above, and for wrappers that inherit from Log4perl use
1996       Log4perl's get_logger function via inheritance, alike.
1997

Access to Internals

1999       The following methods are only of use if you want to peek/poke in the
2000       internals of Log::Log4perl. Be careful not to disrupt its inner
2001       workings.
2002
2003       "Log::Log4perl->appenders()"
2004           To find out which appenders are currently defined (not only for a
2005           particular logger, but overall), a appenders() method is available
2006           to return a reference to a hash mapping appender names to their
2007           Log::Log4perl::Appender object references.
2008

Dirty Tricks

2010       infiltrate_lwp()
2011           The famous LWP::UserAgent module isn't Log::Log4perl-enabled.
2012           Often, though, especially when tracing Web-related problems, it
2013           would be helpful to get some insight on what's happening inside
2014           LWP::UserAgent. Ideally, LWP::UserAgent would even play along in
2015           the Log::Log4perl framework.
2016
2017           A call to "Log::Log4perl->infiltrate_lwp()" does exactly this.  In
2018           a very rude way, it pulls the rug from under LWP::UserAgent and
2019           transforms its "debug/conn" messages into debug() calls of loggers
2020           of the category "LWP::UserAgent". Similarily, "LWP::UserAgent"'s
2021           "trace" messages are turned into "Log::Log4perl"'s info() method
2022           calls. Note that this only works for LWP::UserAgent versions <
2023           5.822, because this (and probably later) versions miss debugging
2024           functions entirely.
2025
2026       Suppressing 'duplicate' LOGDIE messages
2027           If a script with a simple Log4perl configuration uses logdie() to
2028           catch errors and stop processing, as in
2029
2030               use Log::Log4perl qw(:easy) ;
2031               Log::Log4perl->easy_init($DEBUG);
2032
2033               shaky_function() or LOGDIE "It failed!";
2034
2035           there's a cosmetic problem: The message gets printed twice:
2036
2037               2005/07/10 18:37:14 It failed!
2038               It failed! at ./t line 12
2039
2040           The obvious solution is to use LOGEXIT() instead of LOGDIE(), but
2041           there's also a special tag for Log4perl that suppresses the second
2042           message:
2043
2044               use Log::Log4perl qw(:no_extra_logdie_message);
2045
2046           This causes logdie() and logcroak() to call exit() instead of
2047           die(). To modify the script exit code in these occasions, set the
2048           variable $Log::Log4perl::LOGEXIT_CODE to the desired value, the
2049           default is 1.
2050
2051       Redefine values without causing errors
2052           Log4perl's configuration file parser has a few basic safety
2053           mechanisms to make sure configurations are more or less sane.
2054
2055           One of these safety measures is catching redefined values. For
2056           example, if you first write
2057
2058               log4perl.category = WARN, Logfile
2059
2060           and then a couple of lines later
2061
2062               log4perl.category = TRACE, Logfile
2063
2064           then you might have unintentionally overwritten the first value and
2065           Log4perl will die on this with an error (suspicious configurations
2066           always throw an error). Now, there's a chance that this is
2067           intentional, for example when you're lumping together several
2068           configuration files and actually want the first value to overwrite
2069           the second. In this case use
2070
2071               use Log::Log4perl qw(:nostrict);
2072
2073           to put Log4perl in a more permissive mode.
2074
2075       Prevent croak/confess from stringifying
2076           The logcroak/logconfess functions stringify their arguments before
2077           they pass them to Carp's croak/confess functions. This can get in
2078           the way if you want to throw an object or a hashref as an
2079           exception, in this case use:
2080
2081               $Log::Log4perl::STRINGIFY_DIE_MESSAGE = 0;
2082
2083               eval {
2084                     # throws { foo => "bar" }
2085                     # without stringification
2086                   $logger->logcroak( { foo => "bar" } );
2087               };
2088

EXAMPLE

2090       A simple example to cut-and-paste and get started:
2091
2092           use Log::Log4perl qw(get_logger);
2093
2094           my $conf = q(
2095           log4perl.category.Bar.Twix         = WARN, Logfile
2096           log4perl.appender.Logfile          = Log::Log4perl::Appender::File
2097           log4perl.appender.Logfile.filename = test.log
2098           log4perl.appender.Logfile.layout = \
2099               Log::Log4perl::Layout::PatternLayout
2100           log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
2101           );
2102
2103           Log::Log4perl::init(\$conf);
2104
2105           my $logger = get_logger("Bar::Twix");
2106           $logger->error("Blah");
2107
2108       This will log something like
2109
2110           2002/09/19 23:48:15 t1 25> Blah
2111
2112       to the log file "test.log", which Log4perl will append to or create it
2113       if it doesn't exist already.
2114

INSTALLATION

2116       If you want to use external appenders provided with "Log::Dispatch",
2117       you need to install "Log::Dispatch" (2.00 or better) from CPAN, which
2118       itself depends on "Attribute-Handlers" and "Params-Validate". And a lot
2119       of other modules, that's the reason why we're now shipping
2120       Log::Log4perl with its own standard appenders and only if you wish to
2121       use additional ones, you'll have to go through the "Log::Dispatch"
2122       installation process.
2123
2124       Log::Log4perl needs "Test::More", "Test::Harness" and "File::Spec", but
2125       they already come with fairly recent versions of perl.  If not,
2126       everything's automatically fetched from CPAN if you're using the CPAN
2127       shell (CPAN.pm), because they're listed as dependencies.
2128
2129       "Time::HiRes" (1.20 or better) is required only if you need the fine-
2130       grained time stamps of the %r parameter in
2131       "Log::Log4perl::Layout::PatternLayout".
2132
2133       Manual installation works as usual with
2134
2135           perl Makefile.PL
2136           make
2137           make test
2138           make install
2139

DEVELOPMENT

2141       Log::Log4perl is still being actively developed. We will always make
2142       sure the test suite (approx. 500 cases) will pass, but there might
2143       still be bugs. please check <http://github.com/mschilli/log4perl> for
2144       the latest release. The api has reached a mature state, we will not
2145       change it unless for a good reason.
2146
2147       Bug reports and feedback are always welcome, just email them to our
2148       mailing list shown in the AUTHORS section. We're usually addressing
2149       them immediately.
2150

REFERENCES

2152       [1] Michael Schilli, "Retire your debugger, log smartly with
2153           Log::Log4perl!", Tutorial on perl.com, 09/2002,
2154           <http://www.perl.com/pub/a/2002/09/11/log4perl.html>
2155
2156       [2] Ceki Gülcü, "Short introduction to log4j",
2157           <http://logging.apache.org/log4j/1.2/manual.html>
2158
2159       [3] Vipan Singla, "Don't Use System.out.println! Use Log4j.",
2160           <http://www.vipan.com/htdocs/log4jhelp.html>
2161
2162       [4] The Log::Log4perl project home page: <http://log4perl.com>
2163

SEE ALSO

2165       Log::Log4perl::Config, Log::Log4perl::Appender,
2166       Log::Log4perl::Layout::PatternLayout,
2167       Log::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level,
2168       Log::Log4perl::JavaMap Log::Log4perl::NDC,
2169

AUTHORS

2171       Please contribute patches to the project on Github:
2172
2173           http://github.com/mschilli/log4perl
2174
2175       Send bug reports or requests for enhancements to the authors via our
2176
2177       MAILING LIST (questions, bug reports, suggestions/patches):
2178       log4perl-devel@lists.sourceforge.net
2179
2180       Authors (please contact them via the list above, not directly): Mike
2181       Schilli <m@perlmeister.com>, Kevin Goess <cpan@goess.org>
2182
2183       Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens
2184       Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse
2185       Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis
2186       Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier, David
2187       Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
2188       Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars
2189       Thegler, David Viner, Mac Yang.
2190

LICENSE

2192       Copyright 2002-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess
2193       <cpan@goess.org>.
2194
2195       This library is free software; you can redistribute it and/or modify it
2196       under the same terms as Perl itself.
2197
2198
2199
2200perl v5.36.0                      2023-01-20                  Log::Log4perl(3)
Impressum