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