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