Server IP : 103.119.228.120 / Your IP : 3.138.124.28 Web Server : Apache System : Linux v8.techscape8.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64 User : nobody ( 99) PHP Version : 5.6.40 Disable Function : shell_exec,symlink,system,exec,proc_get_status,proc_nice,proc_terminate,define_syslog_variables,syslog,openlog,closelog,escapeshellcmd,passthru,ocinum cols,ini_alter,leak,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dl,dll,myshellexec,proc_open,socket_bind,proc_close,escapeshellarg,parse_ini_filepopen,fpassthru,exec,passthru,escapeshellarg,escapeshellcmd,proc_close,proc_open,ini_alter,popen,show_source,proc_nice,proc_terminate,proc_get_status,proc_close,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,dl,symlink,shell_exec,system,dl,passthru,escapeshellarg,escapeshellcmd,myshellexec,c99_buff_prepare,c99_sess_put,fpassthru,getdisfunc,fx29exec,fx29exec2,is_windows,disp_freespace,fx29sh_getupdate,fx29_buff_prepare,fx29_sess_put,fx29shexit,fx29fsearch,fx29ftpbrutecheck,fx29sh_tools,fx29sh_about,milw0rm,imagez,sh_name,myshellexec,checkproxyhost,dosyayicek,c99_buff_prepare,c99_sess_put,c99getsource,c99sh_getupdate,c99fsearch,c99shexit,view_perms,posix_getpwuid,posix_getgrgid,posix_kill,parse_perms,parsesort,view_perms_color,set_encoder_input,ls_setcheckboxall,ls_reverse_all,rsg_read,rsg_glob,selfURL,dispsecinfo,unix2DosTime,addFile,system,get_users,view_size,DirFiles,DirFilesWide,DirPrintHTMLHeaders,GetFilesTotal,GetTitles,GetTimeTotal,GetMatchesCount,GetFileMatchesCount,GetResultFiles,fs_copy_dir,fs_copy_obj,fs_move_dir,fs_move_obj,fs_rmdir,SearchText,getmicrotime MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/local/share/man/man3/ |
Upload File : |
.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Log::Log4perl 3" .TH Log::Log4perl 3 "2016-03-18" "perl v5.16.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Log::Log4perl \- Log4j implementation for Perl .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& # Easy mode if you like it simple ... \& \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($ERROR); \& \& DEBUG "This doesn\*(Aqt go anywhere"; \& ERROR "This gets logged"; \& \& # ... or standard mode for more features: \& \& Log::Log4perl::init(\*(Aq/etc/log4perl.conf\*(Aq); \& \& \-\-or\-\- \& \& # Check config every 10 secs \& Log::Log4perl::init_and_watch(\*(Aq/etc/log4perl.conf\*(Aq,10); \& \& \-\-then\-\- \& \& $logger = Log::Log4perl\->get_logger(\*(Aqhouse.bedrm.desk.topdrwr\*(Aq); \& \& $logger\->debug(\*(Aqthis is a debug message\*(Aq); \& $logger\->info(\*(Aqthis is an info message\*(Aq); \& $logger\->warn(\*(Aqetc\*(Aq); \& $logger\->error(\*(Aq..\*(Aq); \& $logger\->fatal(\*(Aq..\*(Aq); \& \& #####/etc/log4perl.conf############################### \& log4perl.logger.house = WARN, FileAppndr1 \& log4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1 \& \& log4perl.appender.FileAppndr1 = Log::Log4perl::Appender::File \& log4perl.appender.FileAppndr1.filename = desk.log \& log4perl.appender.FileAppndr1.layout = \e \& Log::Log4perl::Layout::SimpleLayout \& ###################################################### .Ve .SH "ABSTRACT" .IX Header "ABSTRACT" Log::Log4perl provides a powerful logging \s-1API\s0 for your application .SH "DESCRIPTION" .IX Header "DESCRIPTION" Log::Log4perl lets you remote-control and fine-tune the logging behaviour of your system from the outside. It implements the widely popular (Java-based) Log4j logging package in pure Perl. .PP \&\fBFor a detailed tutorial on Log::Log4perl usage, please read\fR .PP <http://www.perl.com/pub/a/2002/09/11/log4perl.html> .PP Logging beats a debugger if you want to know what's going on in your code during runtime. However, traditional logging packages are too static and generate a flood of log messages in your log files that won't help you. .PP \&\f(CW\*(C`Log::Log4perl\*(C'\fR is different. It allows you to control the number of logging messages generated at three different levels: .IP "\(bu" 4 At a central location in your system (either in a configuration file or in the startup code) you specify \fIwhich components\fR (classes, functions) of your system should generate logs. .IP "\(bu" 4 You specify how detailed the logging of these components should be by specifying logging \fIlevels\fR. .IP "\(bu" 4 You also specify which so-called \fIappenders\fR you want to feed your log messages to (\*(L"Print it to the screen and also append it to /tmp/my.log\*(R") and which format (\*(L"Write the date first, then the file name and line number, and then the log message\*(R") they should be in. .PP This is a very powerful and flexible mechanism. You can turn on and off your logs at any time, specify the level of detail and make that dependent on the subsystem that's currently executed. .PP Let me give you an example: You might find out that your system has a problem in the \&\f(CW\*(C`MySystem::Helpers::ScanDir\*(C'\fR component. Turning on detailed debugging logs all over the system would generate a flood of useless log messages and bog your system down beyond recognition. With \f(CW\*(C`Log::Log4perl\*(C'\fR, however, you can tell the system: "Continue to log only severe errors to the log file. Open a second log file, turn on full debug logs in the \f(CW\*(C`MySystem::Helpers::ScanDir\*(C'\fR component and dump all messages originating from there into the new log file". And all this is possible by just changing the parameters in a configuration file, which your system can re-read even while it's running! .SH "How to use it" .IX Header "How to use it" The \f(CW\*(C`Log::Log4perl\*(C'\fR package can be initialized in two ways: Either via Perl commands or via a \f(CW\*(C`log4j\*(C'\fR\-style configuration file. .SS "Initialize via a configuration file" .IX Subsection "Initialize via a configuration file" This is the easiest way to prepare your system for using \&\f(CW\*(C`Log::Log4perl\*(C'\fR. Use a configuration file like this: .PP .Vb 5 \& ############################################################ \& # A simple root logger with a Log::Log4perl::Appender::File \& # file appender in Perl. \& ############################################################ \& log4perl.rootLogger=ERROR, LOGFILE \& \& log4perl.appender.LOGFILE=Log::Log4perl::Appender::File \& log4perl.appender.LOGFILE.filename=/var/log/myerrs.log \& log4perl.appender.LOGFILE.mode=append \& \& log4perl.appender.LOGFILE.layout=PatternLayout \& log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c \- %m%n .Ve .PP These lines define your standard logger that's appending severe errors to \f(CW\*(C`/var/log/myerrs.log\*(C'\fR, using the format .PP .Vb 1 \& [millisecs] source\-filename line\-number class \- message newline .Ve .PP Assuming that this configuration file is saved as \f(CW\*(C`log.conf\*(C'\fR, you need to read it in the startup section of your code, using the following commands: .PP .Vb 2 \& use Log::Log4perl; \& Log::Log4perl\->init("log.conf"); .Ve .PP After that's done \fIsomewhere\fR in the code, you can retrieve logger objects \fIanywhere\fR in the code. Note that there's no need to carry any logger references around with your functions and methods. You can get a logger anytime via a singleton mechanism: .PP .Vb 2 \& package My::MegaPackage; \& use Log::Log4perl; \& \& sub some_method { \& my($param) = @_; \& \& my $log = Log::Log4perl\->get_logger("My::MegaPackage"); \& \& $log\->debug("Debug message"); \& $log\->info("Info message"); \& $log\->error("Error message"); \& \& ... \& } .Ve .PP With the configuration file above, \f(CW\*(C`Log::Log4perl\*(C'\fR will write \&\*(L"Error message\*(R" to the specified log file, but won't do anything for the \f(CW\*(C`debug()\*(C'\fR and \f(CW\*(C`info()\*(C'\fR calls, because the log level has been set to \f(CW\*(C`ERROR\*(C'\fR for all components in the first line of configuration file shown above. .PP Why \f(CW\*(C`Log::Log4perl\->get_logger\*(C'\fR and not \f(CW\*(C`Log::Log4perl\->new\*(C'\fR? We don't want to create a new object every time. Usually in OO-Programming, you create an object once and use the reference to it to call its methods. However, this requires that you pass around the object to all functions and the last thing we want is pollute each and every function/method we're using with a handle to the \f(CW\*(C`Logger\*(C'\fR: .PP .Vb 3 \& sub function { # Brrrr!! \& my($logger, $some, $other, $parameters) = @_; \& } .Ve .PP Instead, if a function/method wants a reference to the logger, it just calls the Logger's static \f(CW\*(C`get_logger($category)\*(C'\fR method to obtain a reference to the \fIone and only\fR possible logger object of a certain category. That's called a \fIsingleton\fR if you're a Gamma fan. .PP How does the logger know which messages it is supposed to log and which ones to suppress? \&\f(CW\*(C`Log::Log4perl\*(C'\fR works with inheritance: The config file above didn't specify anything about \f(CW\*(C`My::MegaPackage\*(C'\fR. And yet, we've defined a logger of the category \&\f(CW\*(C`My::MegaPackage\*(C'\fR. In this case, \f(CW\*(C`Log::Log4perl\*(C'\fR will walk up the namespace hierarchy (\f(CW\*(C`My\*(C'\fR and then we're at the root) to figure out if a log level is defined somewhere. In the case above, the log level at the root (root \fIalways\fR defines a log level, but not necessarily an appender) defines that the log level is supposed to be \f(CW\*(C`ERROR\*(C'\fR \*(-- meaning that \fI\s-1DEBUG\s0\fR and \fI\s-1INFO\s0\fR messages are suppressed. Note that this 'inheritance' is unrelated to Perl's class inheritance, it is merely related to the logger namespace. By the way, if you're ever in doubt about what a logger's category is, use \f(CW\*(C`$logger\->category()\*(C'\fR to retrieve it. .SS "Log Levels" .IX Subsection "Log Levels" There are six predefined log levels: \f(CW\*(C`FATAL\*(C'\fR, \f(CW\*(C`ERROR\*(C'\fR, \f(CW\*(C`WARN\*(C'\fR, \f(CW\*(C`INFO\*(C'\fR, \&\f(CW\*(C`DEBUG\*(C'\fR, and \f(CW\*(C`TRACE\*(C'\fR (in descending priority). Your configured logging level has to at least match the priority of the logging message. .PP If your configured logging level is \f(CW\*(C`WARN\*(C'\fR, then messages logged with \f(CW\*(C`info()\*(C'\fR, \f(CW\*(C`debug()\*(C'\fR, and \f(CW\*(C`trace()\*(C'\fR will be suppressed. \&\f(CW\*(C`fatal()\*(C'\fR, \f(CW\*(C`error()\*(C'\fR and \f(CW\*(C`warn()\*(C'\fR will make their way through, because their priority is higher or equal than the configured setting. .PP Instead of calling the methods .PP .Vb 6 \& $logger\->trace("..."); # Log a trace message \& $logger\->debug("..."); # Log a debug message \& $logger\->info("..."); # Log a info message \& $logger\->warn("..."); # Log a warn message \& $logger\->error("..."); # Log a error message \& $logger\->fatal("..."); # Log a fatal message .Ve .PP you could also call the \f(CW\*(C`log()\*(C'\fR method with the appropriate level using the constants defined in \f(CW\*(C`Log::Log4perl::Level\*(C'\fR: .PP .Vb 1 \& use Log::Log4perl::Level; \& \& $logger\->log($TRACE, "..."); \& $logger\->log($DEBUG, "..."); \& $logger\->log($INFO, "..."); \& $logger\->log($WARN, "..."); \& $logger\->log($ERROR, "..."); \& $logger\->log($FATAL, "..."); .Ve .PP This form is rarely used, but it comes in handy if you want to log at different levels depending on an exit code of a function: .PP .Vb 1 \& $logger\->log( $exit_level{ $rc }, "..."); .Ve .PP As for needing more logging levels than these predefined ones: It's usually best to steer your logging behaviour via the category mechanism instead. .PP If you need to find out if the currently configured logging level would allow a logger's logging statement to go through, use the logger's \f(CW\*(C`is_\f(CIlevel\f(CW()\*(C'\fR methods: .PP .Vb 6 \& $logger\->is_trace() # True if trace messages would go through \& $logger\->is_debug() # True if debug messages would go through \& $logger\->is_info() # True if info messages would go through \& $logger\->is_warn() # True if warn messages would go through \& $logger\->is_error() # True if error messages would go through \& $logger\->is_fatal() # True if fatal messages would go through .Ve .PP Example: \f(CW\*(C`$logger\->is_warn()\*(C'\fR returns true if the logger's current level, as derived from either the logger's category (or, in absence of that, one of the logger's parent's level setting) is \&\f(CW$WARN\fR, \f(CW$ERROR\fR or \f(CW$FATAL\fR. .PP Also available are a series of more Java-esque functions which return the same values. These are of the format \f(CW\*(C`is\f(CILevel\f(CWEnabled()\*(C'\fR, so \f(CW\*(C`$logger\->isDebugEnabled()\*(C'\fR is synonymous to \&\f(CW\*(C`$logger\->is_debug()\*(C'\fR. .PP These level checking functions will come in handy later, when we want to block unnecessary expensive parameter construction in case the logging level is too low to log the statement anyway, like in: .PP .Vb 3 \& if($logger\->is_error()) { \& $logger\->error("Erroneous array: @super_long_array"); \& } .Ve .PP If we had just written .PP .Vb 1 \& $logger\->error("Erroneous array: @super_long_array"); .Ve .PP then Perl would have interpolated \&\f(CW@super_long_array\fR into the string via an expensive operation only to figure out shortly after that the string can be ignored entirely because the configured logging level is lower than \f(CW$ERROR\fR. .PP The to-be-logged message passed to all of the functions described above can consist of an arbitrary number of arguments, which the logging functions just chain together to a single string. Therefore .PP .Vb 2 \& $logger\->debug("Hello ", "World", "!"); # and \& $logger\->debug("Hello World!"); .Ve .PP are identical. .PP Note that even if one of the methods above returns true, it doesn't necessarily mean that the message will actually get logged. What \fIis_debug()\fR checks is that the logger used is configured to let a message of the given priority (\s-1DEBUG\s0) through. But after this check, Log4perl will eventually apply custom filters and forward the message to one or more appenders. None of this gets checked by \fIis_xxx()\fR, for the simple reason that it's impossible to know what a custom filter does with a message without having the actual message or what an appender does to a message without actually having it log it. .SS "Log and die or warn" .IX Subsection "Log and die or warn" Often, when you croak / carp / warn / die, you want to log those messages. Rather than doing the following: .PP .Vb 1 \& $logger\->fatal($err) && die($err); .Ve .PP you can use the following: .PP .Vb 1 \& $logger\->logdie($err); .Ve .PP And if instead of using .PP .Vb 2 \& warn($message); \& $logger\->warn($message); .Ve .PP to both issue a warning via Perl's \fIwarn()\fR mechanism and make sure you have the same message in the log file as well, use: .PP .Vb 1 \& $logger\->logwarn($message); .Ve .PP Since there is an \s-1ERROR\s0 level between \s-1WARN\s0 and \s-1FATAL,\s0 there are two additional helper functions in case you'd like to use \s-1ERROR\s0 for either \fIwarn()\fR or \fIdie()\fR: .PP .Vb 2 \& $logger\->error_warn(); \& $logger\->error_die(); .Ve .PP Finally, there's the Carp functions that, in addition to logging, also pass the stringified message to their companions in the Carp package: .PP .Vb 4 \& $logger\->logcarp(); # warn w/ 1\-level stack trace \& $logger\->logcluck(); # warn w/ full stack trace \& $logger\->logcroak(); # die w/ 1\-level stack trace \& $logger\->logconfess(); # die w/ full stack trace .Ve .SS "Appenders" .IX Subsection "Appenders" If you don't define any appenders, nothing will happen. Appenders will be triggered whenever the configured logging level requires a message to be logged and not suppressed. .PP \&\f(CW\*(C`Log::Log4perl\*(C'\fR doesn't define any appenders by default, not even the root logger has one. .PP \&\f(CW\*(C`Log::Log4perl\*(C'\fR already comes with a standard set of appenders: .PP .Vb 7 \& Log::Log4perl::Appender::Screen \& Log::Log4perl::Appender::ScreenColoredLevels \& Log::Log4perl::Appender::File \& Log::Log4perl::Appender::Socket \& Log::Log4perl::Appender::DBI \& Log::Log4perl::Appender::Synchronized \& Log::Log4perl::Appender::RRDs .Ve .PP to log to the screen, to files and to databases. .PP On \s-1CPAN,\s0 you can find additional appenders like .PP .Vb 1 \& Log::Log4perl::Layout::XMLLayout .Ve .PP by Guido Carls <gcarls@cpan.org>. It allows for hooking up Log::Log4perl with the graphical Log Analyzer Chainsaw (see \&\*(L"Can I use Log::Log4perl with log4j's Chainsaw?\*(R" in Log::Log4perl::FAQ). .SS "Additional Appenders via Log::Dispatch" .IX Subsection "Additional Appenders via Log::Dispatch" \&\f(CW\*(C`Log::Log4perl\*(C'\fR also supports \fIDave Rolskys\fR excellent \f(CW\*(C`Log::Dispatch\*(C'\fR framework which implements a wide variety of different appenders. .PP Here's the list of appender modules currently available via \f(CW\*(C`Log::Dispatch\*(C'\fR: .PP .Vb 12 \& Log::Dispatch::ApacheLog \& Log::Dispatch::DBI (by Tatsuhiko Miyagawa) \& Log::Dispatch::Email, \& Log::Dispatch::Email::MailSend, \& Log::Dispatch::Email::MailSendmail, \& Log::Dispatch::Email::MIMELite \& Log::Dispatch::File \& Log::Dispatch::FileRotate (by Mark Pfeiffer) \& Log::Dispatch::Handle \& Log::Dispatch::Screen \& Log::Dispatch::Syslog \& Log::Dispatch::Tk (by Dominique Dumont) .Ve .PP Please note that in order to use any of these additional appenders, you have to fetch Log::Dispatch from \s-1CPAN\s0 and install it. Also the particular appender you're using might require installing the particular module. .PP For additional information on appenders, please check the Log::Log4perl::Appender manual page. .SS "Appender Example" .IX Subsection "Appender Example" Now let's assume that we want to log \f(CW\*(C`info()\*(C'\fR or higher prioritized messages in the \f(CW\*(C`Foo::Bar\*(C'\fR category to both \s-1STDOUT\s0 and to a log file, say \f(CW\*(C`test.log\*(C'\fR. In the initialization section of your system, just define two appenders using the readily available \&\f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR and \f(CW\*(C`Log::Log4perl::Appender::Screen\*(C'\fR modules: .PP .Vb 1 \& use Log::Log4perl; \& \& # Configuration in a string ... \& my $conf = q( \& log4perl.category.Foo.Bar = INFO, Logfile, Screen \& \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.layout = Log::Log4perl::Layout::PatternLayout \& log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.stderr = 0 \& log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout \& ); \& \& # ... passed as a reference to init() \& Log::Log4perl::init( \e$conf ); .Ve .PP Once the initialization shown above has happened once, typically in the startup code of your system, just use the defined logger anywhere in your system: .PP .Vb 4 \& ########################## \& # ... in some function ... \& ########################## \& my $log = Log::Log4perl::get_logger("Foo::Bar"); \& \& # Logs both to STDOUT and to the file test.log \& $log\->info("Important Info!"); .Ve .PP The \f(CW\*(C`layout\*(C'\fR settings specified in the configuration section define the format in which the message is going to be logged by the specified appender. The format shown for the file appender is logging not only the message but also the number of milliseconds since the program has started (%r), the name of the file the call to the logger has happened and the line number there (%F and \&\f(CW%L\fR), the message itself (%m) and a OS-specific newline character (%n): .PP .Vb 1 \& [187] ./myscript.pl 27 Important Info! .Ve .PP The screen appender above, on the other hand, uses a \f(CW\*(C`SimpleLayout\*(C'\fR, which logs the debug level, a hyphen (\-) and the log message: .PP .Vb 1 \& INFO \- Important Info! .Ve .PP For more detailed info on layout formats, see \*(L"Log Layouts\*(R". .PP In the configuration sample above, we chose to define a \fIcategory\fR logger (\f(CW\*(C`Foo::Bar\*(C'\fR). This will cause only messages originating from this specific category logger to be logged in the defined format and locations. .SS "Logging newlines" .IX Subsection "Logging newlines" There's some controversy between different logging systems as to when and where newlines are supposed to be added to logged messages. .PP The Log4perl way is that a logging statement \fIshould not\fR contain a newline: .PP .Vb 2 \& $logger\->info("Some message"); \& $logger\->info("Another message"); .Ve .PP If this is supposed to end up in a log file like .PP .Vb 2 \& Some message \& Another message .Ve .PP then an appropriate appender layout like \*(L"%m%n\*(R" will take care of adding a newline at the end of each message to make sure every message is printed on its own line. .PP Other logging systems, Log::Dispatch in particular, recommend adding the newline to the log statement. This doesn't work well, however, if you, say, replace your file appender by a database appender, and all of a sudden those newlines scattered around the code don't make sense anymore. .PP Assigning matching layouts to different appenders and leaving newlines out of the code solves this problem. If you inherited code that has logging statements with newlines and want to make it work with Log4perl, read the Log::Log4perl::Layout::PatternLayout documentation on how to accomplish that. .SS "Configuration files" .IX Subsection "Configuration files" As shown above, you can define \f(CW\*(C`Log::Log4perl\*(C'\fR loggers both from within your Perl code or from configuration files. The latter have the unbeatable advantage that you can modify your system's logging behaviour without interfering with the code at all. So even if your code is being run by somebody who's totally oblivious to Perl, they still can adapt the module's logging behaviour to their needs. .PP \&\f(CW\*(C`Log::Log4perl\*(C'\fR has been designed to understand \f(CW\*(C`Log4j\*(C'\fR configuration files \*(-- as used by the original Java implementation. Instead of reiterating the format description in [2], let me just list three examples (also derived from [2]), which should also illustrate how it works: .PP .Vb 4 \& log4j.rootLogger=DEBUG, A1 \& log4j.appender.A1=org.apache.log4j.ConsoleAppender \& log4j.appender.A1.layout=org.apache.log4j.PatternLayout \& log4j.appender.A1.layout.ConversionPattern=%\-4r %\-5p %c %x \- %m%n .Ve .PP This enables messages of priority \f(CW\*(C`DEBUG\*(C'\fR or higher in the root hierarchy and has the system write them to the console. \&\f(CW\*(C`ConsoleAppender\*(C'\fR is a Java appender, but \f(CW\*(C`Log::Log4perl\*(C'\fR jumps through a significant number of hoops internally to map these to their corresponding Perl classes, \f(CW\*(C`Log::Log4perl::Appender::Screen\*(C'\fR in this case. .PP Second example: .PP .Vb 5 \& log4perl.rootLogger=DEBUG, A1 \& log4perl.appender.A1=Log::Log4perl::Appender::Screen \& log4perl.appender.A1.layout=PatternLayout \& log4perl.appender.A1.layout.ConversionPattern=%d %\-5p %c \- %m%n \& log4perl.logger.com.foo=WARN .Ve .PP This defines two loggers: The root logger and the \f(CW\*(C`com.foo\*(C'\fR logger. The root logger is easily triggered by debug-messages, but the \f(CW\*(C`com.foo\*(C'\fR logger makes sure that messages issued within the \f(CW\*(C`Com::Foo\*(C'\fR component and below are only forwarded to the appender if they're of priority \fIwarning\fR or higher. .PP Note that the \f(CW\*(C`com.foo\*(C'\fR logger doesn't define an appender. Therefore, it will just propagate the message up the hierarchy until the root logger picks it up and forwards it to the one and only appender of the root category, using the format defined for it. .PP Third example: .PP .Vb 8 \& log4j.rootLogger=DEBUG, stdout, R \& log4j.appender.stdout=org.apache.log4j.ConsoleAppender \& log4j.appender.stdout.layout=org.apache.log4j.PatternLayout \& log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) \- %m%n \& log4j.appender.R=org.apache.log4j.RollingFileAppender \& log4j.appender.R.File=example.log \& log4j.appender.R.layout=org.apache.log4j.PatternLayout \& log4j.appender.R.layout.ConversionPattern=%p %c \- %m%n .Ve .PP The root logger defines two appenders here: \f(CW\*(C`stdout\*(C'\fR, which uses \&\f(CW\*(C`org.apache.log4j.ConsoleAppender\*(C'\fR (ultimately mapped by \f(CW\*(C`Log::Log4perl\*(C'\fR to Log::Log4perl::Appender::Screen) to write to the screen. And \&\f(CW\*(C`R\*(C'\fR, a \f(CW\*(C`org.apache.log4j.RollingFileAppender\*(C'\fR (mapped by \f(CW\*(C`Log::Log4perl\*(C'\fR to Log::Dispatch::FileRotate with the \f(CW\*(C`File\*(C'\fR attribute specifying the log file. .PP See Log::Log4perl::Config for more examples and syntax explanations. .SS "Log Layouts" .IX Subsection "Log Layouts" If the logging engine passes a message to an appender, because it thinks it should be logged, the appender doesn't just write it out haphazardly. There's ways to tell the appender how to format the message and add all sorts of interesting data to it: The date and time when the event happened, the file, the line number, the debug level of the logger and others. .PP There's currently two layouts defined in \f(CW\*(C`Log::Log4perl\*(C'\fR: \&\f(CW\*(C`Log::Log4perl::Layout::SimpleLayout\*(C'\fR and \&\f(CW\*(C`Log::Log4perl::Layout::PatternLayout\*(C'\fR: .ie n .IP """Log::Log4perl::SimpleLayout""" 4 .el .IP "\f(CWLog::Log4perl::SimpleLayout\fR" 4 .IX Item "Log::Log4perl::SimpleLayout" formats a message in a simple way and just prepends it by the debug level and a hyphen: \&\f(CW\*(C`"$level \- $message\*(C'\fR, for example \f(CW"FATAL \- Can\*(Aqt open password file"\fR. .ie n .IP """Log::Log4perl::Layout::PatternLayout""" 4 .el .IP "\f(CWLog::Log4perl::Layout::PatternLayout\fR" 4 .IX Item "Log::Log4perl::Layout::PatternLayout" on the other hand is very powerful and allows for a very flexible format in \f(CW\*(C`printf\*(C'\fR\-style. The format string can contain a number of placeholders which will be replaced by the logging engine when it's time to log the message: .Sp .Vb 10 \& %c Category of the logging event. \& %C Fully qualified package (or class) name of the caller \& %d Current date in yyyy/MM/dd hh:mm:ss format \& %F File where the logging event occurred \& %H Hostname (if Sys::Hostname is available) \& %l Fully qualified name of the calling method followed by the \& callers source the file name and line number between \& parentheses. \& %L Line number within the file where the log statement was issued \& %m The message to be logged \& %m{chomp} The message to be logged, stripped off a trailing newline \& %M Method or function where the logging request was issued \& %n Newline (OS\-independent) \& %p Priority of the logging event \& %P pid of the current process \& %r Number of milliseconds elapsed from program start to logging \& event \& %R Number of milliseconds elapsed from last logging event to \& current logging event \& %T A stack trace of functions called \& %x The topmost NDC (see below) \& %X{key} The entry \*(Aqkey\*(Aq of the MDC (see below) \& %% A literal percent (%) sign .Ve .Sp \&\s-1NDC\s0 and \s-1MDC\s0 are explained in \*(L"Nested Diagnostic Context (\s-1NDC\s0)\*(R" and \*(L"Mapped Diagnostic Context (\s-1MDC\s0)\*(R". .Sp Also, \f(CW%d\fR can be fine-tuned to display only certain characteristics of a date, according to the SimpleDateFormat in the Java World (<http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html>) .Sp In this way, \f(CW%d{HH:mm}\fR displays only hours and minutes of the current date, while \f(CW%d{yy, EEEE}\fR displays a two-digit year, followed by a spelled-out day (like \f(CW\*(C`Wednesday\*(C'\fR). .Sp Similar options are available for shrinking the displayed category or limit file/path components, \f(CW%F{1}\fR only displays the source file \fIname\fR without any path components while \f(CW%F\fR logs the full path. \f(CW%c\fR{2} only logs the last two components of the current category, \f(CW\*(C`Foo::Bar::Baz\*(C'\fR becomes \f(CW\*(C`Bar::Baz\*(C'\fR and saves space. .Sp If those placeholders aren't enough, then you can define your own right in the config file like this: .Sp .Vb 1 \& log4perl.PatternLayout.cspec.U = sub { return "UID $<" } .Ve .Sp See Log::Log4perl::Layout::PatternLayout for further details on customized specifiers. .Sp Please note that the subroutines you're defining in this way are going to be run in the \f(CW\*(C`main\*(C'\fR namespace, so be sure to fully qualify functions and variables if they're located in different packages. .Sp \&\s-1SECURITY NOTE:\s0 this feature means arbitrary perl code can be embedded in the config file. In the rare case where the people who have access to your config file are different from the people who write your code and shouldn't have execute rights, you might want to call .Sp .Vb 1 \& Log::Log4perl::Config\->allow_code(0); .Ve .Sp before you call \fIinit()\fR. Alternatively you can supply a restricted set of Perl opcodes that can be embedded in the config file as described in \&\*(L"Restricting what Opcodes can be in a Perl Hook\*(R". .PP All placeholders are quantifiable, just like in \fIprintf\fR. Following this tradition, \f(CW\*(C`%\-20c\*(C'\fR will reserve 20 chars for the category and left-justify it. .PP For more details on logging and how to use the flexible and the simple format, check out the original \f(CW\*(C`log4j\*(C'\fR website under .PP SimpleLayout <http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/SimpleLayout.html> and PatternLayout <http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html> .SS "Penalties" .IX Subsection "Penalties" Logging comes with a price tag. \f(CW\*(C`Log::Log4perl\*(C'\fR has been optimized to allow for maximum performance, both with logging enabled and disabled. .PP But you need to be aware that there's a small hit every time your code encounters a log statement \*(-- no matter if logging is enabled or not. \&\f(CW\*(C`Log::Log4perl\*(C'\fR has been designed to keep this so low that it will be unnoticeable to most applications. .PP Here's a couple of tricks which help \f(CW\*(C`Log::Log4perl\*(C'\fR to avoid unnecessary delays: .PP You can save serious time if you're logging something like .PP .Vb 4 \& # Expensive in non\-debug mode! \& for (@super_long_array) { \& $logger\->debug("Element: $_"); \& } .Ve .PP and \f(CW@super_long_array\fR is fairly big, so looping through it is pretty expensive. Only you, the programmer, knows that going through that \f(CW\*(C`for\*(C'\fR loop can be skipped entirely if the current logging level for the actual component is higher than \f(CW\*(C`debug\*(C'\fR. In this case, use this instead: .PP .Vb 6 \& # Cheap in non\-debug mode! \& if($logger\->is_debug()) { \& for (@super_long_array) { \& $logger\->debug("Element: $_"); \& } \& } .Ve .PP If you're afraid that generating the parameters to the logging function is fairly expensive, use closures: .PP .Vb 3 \& # Passed as subroutine ref \& use Data::Dumper; \& $logger\->debug(sub { Dumper($data) } ); .Ve .PP This won't unravel \f(CW$data\fR via \fIDumper()\fR unless it's actually needed because it's logged. .PP Also, Log::Log4perl lets you specify arguments to logger functions in \fImessage output filter syntax\fR: .PP .Vb 3 \& $logger\->debug("Structure: ", \& { filter => \e&Dumper, \& value => $someref }); .Ve .PP In this way, shortly before Log::Log4perl sending the message out to any appenders, it will be searching all arguments for hash references and treat them in a special way: .PP It will invoke the function given as a reference with the \f(CW\*(C`filter\*(C'\fR key (\f(CW\*(C`Data::Dumper::Dumper()\*(C'\fR) and pass it the value that came with the key named \f(CW\*(C`value\*(C'\fR as an argument. The anonymous hash in the call above will be replaced by the return value of the filter function. .SH "Categories" .IX Header "Categories" \&\fBCategories are also called \*(L"Loggers\*(R" in Log4perl, both refer to the same thing and these terms are used interchangeably.\fR \&\f(CW\*(C`Log::Log4perl\*(C'\fR uses \fIcategories\fR to determine if a log statement in a component should be executed or suppressed at the current logging level. Most of the time, these categories are just the classes the log statements are located in: .PP .Vb 1 \& package Candy::Twix; \& \& sub new { \& my $logger = Log::Log4perl\->get_logger("Candy::Twix"); \& $logger\->debug("Creating a new Twix bar"); \& bless {}, shift; \& } \& \& # ... \& \& package Candy::Snickers; \& \& sub new { \& my $logger = Log::Log4perl\->get_logger("Candy.Snickers"); \& $logger\->debug("Creating a new Snickers bar"); \& bless {}, shift; \& } \& \& # ... \& \& package main; \& Log::Log4perl\->init("mylogdefs.conf"); \& \& # => "LOG> Creating a new Snickers bar" \& my $first = Candy::Snickers\->new(); \& # => "LOG> Creating a new Twix bar" \& my $second = Candy::Twix\->new(); .Ve .PP Note that you can separate your category hierarchy levels using either dots like in Java (.) or double-colons (::) like in Perl. Both notations are equivalent and are handled the same way internally. .PP However, categories are just there to make use of inheritance: if you invoke a logger in a sub-category, it will bubble up the hierarchy and call the appropriate appenders. Internally, categories are not related to the class hierarchy of the program at all \*(-- they're purely virtual. You can use arbitrary categories \*(-- for example in the following program, which isn't oo-style, but procedural: .PP .Vb 1 \& sub print_portfolio { \& \& my $log = Log::Log4perl\->get_logger("user.portfolio"); \& $log\->debug("Quotes requested: @_"); \& \& for(@_) { \& print "$_: ", get_quote($_), "\en"; \& } \& } \& \& sub get_quote { \& \& my $log = Log::Log4perl\->get_logger("internet.quotesystem"); \& $log\->debug("Fetching quote: $_[0]"); \& \& return yahoo_quote($_[0]); \& } .Ve .PP The logger in first function, \f(CW\*(C`print_portfolio\*(C'\fR, is assigned the (virtual) \f(CW\*(C`user.portfolio\*(C'\fR category. Depending on the \f(CW\*(C`Log4perl\*(C'\fR configuration, this will either call a \f(CW\*(C`user.portfolio\*(C'\fR appender, a \f(CW\*(C`user\*(C'\fR appender, or an appender assigned to root \*(-- without \&\f(CW\*(C`user.portfolio\*(C'\fR having any relevance to the class system used in the program. The logger in the second function adheres to the \&\f(CW\*(C`internet.quotesystem\*(C'\fR category \*(-- again, maybe because it's bundled with other Internet functions, but not because there would be a class of this name somewhere. .PP However, be careful, don't go overboard: if you're developing a system in object-oriented style, using the class hierarchy is usually your best choice. Think about the people taking over your code one day: The class hierarchy is probably what they know right up front, so it's easy for them to tune the logging to their needs. .SS "Turn off a component" .IX Subsection "Turn off a component" \&\f(CW\*(C`Log4perl\*(C'\fR doesn't only allow you to selectively switch \fIon\fR a category of log messages, you can also use the mechanism to selectively \fIdisable\fR logging in certain components whereas logging is kept turned on in higher-level categories. This mechanism comes in handy if you find that while bumping up the logging level of a high-level (i. e. close to root) category, that one component logs more than it should, .PP Here's how it works: .PP .Vb 6 \& ############################################################ \& # Turn off logging in a lower\-level category while keeping \& # it active in higher\-level categories. \& ############################################################ \& log4perl.rootLogger=DEBUG, LOGFILE \& log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE \& \& # ... Define appenders ... .Ve .PP This way, log messages issued from within \&\f(CW\*(C`Deep::Down::The::Hierarchy\*(C'\fR and below will be logged only if they're \f(CW\*(C`ERROR\*(C'\fR or worse, while in all other system components even \f(CW\*(C`DEBUG\*(C'\fR messages will be logged. .SS "Return Values" .IX Subsection "Return Values" All logging methods return values indicating if their message actually reached one or more appenders. If the message has been suppressed because of level constraints, \f(CW\*(C`undef\*(C'\fR is returned. .PP For example, .PP .Vb 1 \& my $ret = $logger\->info("Message"); .Ve .PP will return \f(CW\*(C`undef\*(C'\fR if the system debug level for the current category is not \f(CW\*(C`INFO\*(C'\fR or more permissive. If Log::Log4perl forwarded the message to one or more appenders, the number of appenders is returned. .PP If appenders decide to veto on the message with an appender threshold, the log method's return value will have them excluded. This means that if you've got one appender holding an appender threshold and you're logging a message which passes the system's log level hurdle but not the appender threshold, \&\f(CW0\fR will be returned by the log function. .PP The bottom line is: Logging functions will return a \fItrue\fR value if the message made it through to one or more appenders and a \fIfalse\fR value if it didn't. This allows for constructs like .PP .Vb 1 \& $logger\->fatal("@_") or print STDERR "@_\en"; .Ve .PP which will ensure that the fatal message isn't lost if the current level is lower than \s-1FATAL\s0 or printed twice if the level is acceptable but an appender already points to \s-1STDERR.\s0 .SS "Pitfalls with Categories" .IX Subsection "Pitfalls with Categories" Be careful with just blindly reusing the system's packages as categories. If you do, you'll get into trouble with inherited methods. Imagine the following class setup: .PP .Vb 1 \& use Log::Log4perl; \& \& ########################################### \& package Bar; \& ########################################### \& sub new { \& my($class) = @_; \& my $logger = Log::Log4perl::get_logger(_\|_PACKAGE_\|_); \& $logger\->debug("Creating instance"); \& bless {}, $class; \& } \& ########################################### \& package Bar::Twix; \& ########################################### \& our @ISA = qw(Bar); \& \& ########################################### \& package main; \& ########################################### \& Log::Log4perl\->init(\e qq{ \& log4perl.category.Bar.Twix = DEBUG, Screen \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = SimpleLayout \& }); \& \& my $bar = Bar::Twix\->new(); .Ve .PP \&\f(CW\*(C`Bar::Twix\*(C'\fR just inherits everything from \f(CW\*(C`Bar\*(C'\fR, including the constructor \&\f(CW\*(C`new()\*(C'\fR. Contrary to what you might be thinking at first, this won't log anything. Reason for this is the \f(CW\*(C`get_logger()\*(C'\fR call in package \f(CW\*(C`Bar\*(C'\fR, which will always get a logger of the \f(CW\*(C`Bar\*(C'\fR category, even if we call \f(CW\*(C`new()\*(C'\fR via the \f(CW\*(C`Bar::Twix\*(C'\fR package, which will make perl go up the inheritance tree to actually execute \f(CW\*(C`Bar::new()\*(C'\fR. Since we've only defined logging behaviour for \f(CW\*(C`Bar::Twix\*(C'\fR in the configuration file, nothing will happen. .PP This can be fixed by changing the \f(CW\*(C`get_logger()\*(C'\fR method in \f(CW\*(C`Bar::new()\*(C'\fR to obtain a logger of the category matching the \&\fIactual\fR class of the object, like in .PP .Vb 2 \& # ... in Bar::new() ... \& my $logger = Log::Log4perl::get_logger( $class ); .Ve .PP In a method other than the constructor, the class name of the actual object can be obtained by calling \f(CW\*(C`ref()\*(C'\fR on the object reference, so .PP .Vb 2 \& package BaseClass; \& use Log::Log4perl qw( get_logger ); \& \& sub new { \& bless {}, shift; \& } \& \& sub method { \& my( $self ) = @_; \& \& get_logger( ref $self )\->debug( "message" ); \& } \& \& package SubClass; \& our @ISA = qw(BaseClass); .Ve .PP is the recommended pattern to make sure that .PP .Vb 2 \& my $sub = SubClass\->new(); \& $sub\->meth(); .Ve .PP starts logging if the \f(CW"SubClass"\fR category (and not the \f(CW"BaseClass"\fR category has logging enabled at the \s-1DEBUG\s0 level. .SS "Initialize once and only once" .IX Subsection "Initialize once and only once" It's important to realize that Log::Log4perl gets initialized once and only once, typically at the start of a program or system. Calling \f(CW\*(C`init()\*(C'\fR more than once will cause it to clobber the existing configuration and \&\fIreplace\fR it by the new one. .PP If you're in a traditional \s-1CGI\s0 environment, where every request is handled by a new process, calling \f(CW\*(C`init()\*(C'\fR every time is fine. In persistent environments like \f(CW\*(C`mod_perl\*(C'\fR, however, Log::Log4perl should be initialized either at system startup time (Apache offers startup handlers for that) or via .PP .Vb 2 \& # Init or skip if already done \& Log::Log4perl\->init_once($conf_file); .Ve .PP \&\f(CW\*(C`init_once()\*(C'\fR is identical to \f(CW\*(C`init()\*(C'\fR, just with the exception that it will leave a potentially existing configuration alone and will only call \f(CW\*(C`init()\*(C'\fR if Log::Log4perl hasn't been initialized yet. .PP If you're just curious if Log::Log4perl has been initialized yet, the check .PP .Vb 5 \& if(Log::Log4perl\->initialized()) { \& # Yes, Log::Log4perl has already been initialized \& } else { \& # No, not initialized yet ... \& } .Ve .PP can be used. .PP If you're afraid that the components of your system are stepping on each other's toes or if you are thinking that different components should initialize Log::Log4perl separately, try to consolidate your system to use a centralized Log4perl configuration file and use Log4perl's \fIcategories\fR to separate your components. .SS "Custom Filters" .IX Subsection "Custom Filters" Log4perl allows the use of customized filters in its appenders to control the output of messages. These filters might grep for certain text chunks in a message, verify that its priority matches or exceeds a certain level or that this is the 10th time the same message has been submitted \*(-- and come to a log/no log decision based upon these circumstantial facts. .PP Check out Log::Log4perl::Filter for detailed instructions on how to use them. .SS "Performance" .IX Subsection "Performance" The performance of Log::Log4perl calls obviously depends on a lot of things. But to give you a general idea, here's some rough numbers: .PP On a Pentium 4 Linux box at 2.4 GHz, you'll get through .IP "\(bu" 4 500,000 suppressed log statements per second .IP "\(bu" 4 30,000 logged messages per second (using an in-memory appender) .IP "\(bu" 4 init_and_watch delay mode: 300,000 suppressed, 30,000 logged. init_and_watch signal mode: 450,000 suppressed, 30,000 logged. .PP Numbers depend on the complexity of the Log::Log4perl configuration. For a more detailed benchmark test, check the \f(CW\*(C`docs/benchmark.results.txt\*(C'\fR document in the Log::Log4perl distribution. .SH "Cool Tricks" .IX Header "Cool Tricks" Here's a collection of useful tricks for the advanced \f(CW\*(C`Log::Log4perl\*(C'\fR user. For more, check the \s-1FAQ,\s0 either in the distribution (Log::Log4perl::FAQ) or on <http://log4perl.sourceforge.net>. .SS "Shortcuts" .IX Subsection "Shortcuts" When getting an instance of a logger, instead of saying .PP .Vb 2 \& use Log::Log4perl; \& my $logger = Log::Log4perl\->get_logger(); .Ve .PP it's often more convenient to import the \f(CW\*(C`get_logger\*(C'\fR method from \&\f(CW\*(C`Log::Log4perl\*(C'\fR into the current namespace: .PP .Vb 2 \& use Log::Log4perl qw(get_logger); \& my $logger = get_logger(); .Ve .PP Please note this difference: To obtain the root logger, please use \&\f(CW\*(C`get_logger("")\*(C'\fR, call it without parameters (\f(CW\*(C`get_logger()\*(C'\fR), you'll get the logger of a category named after the current package. \&\f(CW\*(C`get_logger()\*(C'\fR is equivalent to \f(CW\*(C`get_logger(_\|_PACKAGE_\|_)\*(C'\fR. .SS "Alternative initialization" .IX Subsection "Alternative initialization" Instead of having \f(CW\*(C`init()\*(C'\fR read in a configuration file by specifying a file name or passing it a reference to an open filehandle (\f(CW\*(C`Log::Log4perl\->init( \e*FILE )\*(C'\fR), you can also pass in a reference to a string, containing the content of the file: .PP .Vb 1 \& Log::Log4perl\->init( \e$config_text ); .Ve .PP Also, if you've got the \f(CW\*(C`name=value\*(C'\fR pairs of the configuration in a hash, you can just as well initialize \f(CW\*(C`Log::Log4perl\*(C'\fR with a reference to it: .PP .Vb 5 \& my %key_value_pairs = ( \& "log4perl.rootLogger" => "ERROR, LOGFILE", \& "log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File", \& ... \& ); \& \& Log::Log4perl\->init( \e%key_value_pairs ); .Ve .PP Or also you can use a \s-1URL,\s0 see below: .SS "Using \s-1LWP\s0 to parse URLs" .IX Subsection "Using LWP to parse URLs" (This section borrowed from XML::DOM::Parser by T.J. Mather). .PP The \fIinit()\fR function now also supports URLs, e.g. \fIhttp://www.erols.com/enno/xsa.xml\fR. It uses \s-1LWP\s0 to download the file and then calls \fIparse()\fR on the resulting string. By default it will use a LWP::UserAgent that is created as follows: .PP .Vb 3 \& use LWP::UserAgent; \& $LWP_USER_AGENT = LWP::UserAgent\->new; \& $LWP_USER_AGENT\->env_proxy; .Ve .PP Note that env_proxy reads proxy settings from environment variables, which is what Log4perl needs to do to get through our firewall. If you want to use a different LWP::UserAgent, you can set it with .PP .Vb 1 \& Log::Log4perl::Config::set_LWP_UserAgent($my_agent); .Ve .PP Currently, \s-1LWP\s0 is used when the filename (passed to parsefile) starts with one of the following \s-1URL\s0 schemes: http, https, ftp, wais, gopher, or file (followed by a colon.) .PP Don't use this feature with \fIinit_and_watch()\fR. .SS "Automatic reloading of changed configuration files" .IX Subsection "Automatic reloading of changed configuration files" Instead of just statically initializing Log::Log4perl via .PP .Vb 1 \& Log::Log4perl\->init($conf_file); .Ve .PP there's a way to have Log::Log4perl periodically check for changes in the configuration and reload it if necessary: .PP .Vb 1 \& Log::Log4perl\->init_and_watch($conf_file, $delay); .Ve .PP In this mode, Log::Log4perl will examine the configuration file \&\f(CW$conf_file\fR every \f(CW$delay\fR seconds for changes via the file's last modification timestamp. If the file has been updated, it will be reloaded and replace the current Log::Log4perl configuration. .PP The way this works is that with every logger function called (\fIdebug()\fR, \fIis_debug()\fR, etc.), Log::Log4perl will check if the delay interval has expired. If so, it will run a \-M file check on the configuration file. If its timestamp has been modified, the current configuration will be dumped and new content of the file will be loaded. .PP This convenience comes at a price, though: Calling \fItime()\fR with every logging function call, especially the ones that are \*(L"suppressed\*(R" (!), will slow down these Log4perl calls by about 40%. .PP To alleviate this performance hit a bit, \f(CW\*(C`init_and_watch()\*(C'\fR can be configured to listen for a Unix signal to reload the configuration instead: .PP .Vb 1 \& Log::Log4perl\->init_and_watch($conf_file, \*(AqHUP\*(Aq); .Ve .PP This will set up a signal handler for \s-1SIGHUP\s0 and reload the configuration if the application receives this signal, e.g. via the \f(CW\*(C`kill\*(C'\fR command: .PP .Vb 1 \& kill \-HUP pid .Ve .PP where \f(CW\*(C`pid\*(C'\fR is the process \s-1ID\s0 of the application. This will bring you back to about 85% of Log::Log4perl's normal execution speed for suppressed statements. For details, check out \*(L"Performance\*(R". For more info on the signal handler, look for \*(L"\s-1SIGNAL MODE\*(R"\s0 in Log::Log4perl::Config::Watch. .PP If you have a somewhat long delay set between physical config file checks or don't want to use the signal associated with the config file watcher, you can trigger a configuration reload at the next possible time by calling \f(CW\*(C`Log::Log4perl::Config\->watcher\->force_next_check()\*(C'\fR. .PP One thing to watch out for: If the configuration file contains a syntax or other fatal error, a running application will stop with \f(CW\*(C`die\*(C'\fR if this damaged configuration will be loaded during runtime, triggered either by a signal or if the delay period expired and the change is detected. This behaviour might change in the future. .PP To allow the application to intercept and control a configuration reload in init_and_watch mode, a callback can be specified: .PP .Vb 2 \& Log::Log4perl\->init_and_watch($conf_file, 10, { \& preinit_callback => \e&callback }); .Ve .PP If Log4perl determines that the configuration needs to be reloaded, it will call the \f(CW\*(C`preinit_callback\*(C'\fR function without parameters. If the callback returns a true value, Log4perl will proceed and reload the configuration. If the callback returns a false value, Log4perl will keep the old configuration and skip reloading it until the next time around. Inside the callback, an application can run all kinds of checks, including accessing the configuration file, which is available via \&\f(CW\*(C`Log::Log4perl::Config\->watcher()\->file()\*(C'\fR. .SS "Variable Substitution" .IX Subsection "Variable Substitution" To avoid having to retype the same expressions over and over again, Log::Log4perl's configuration files support simple variable substitution. New variables are defined simply by adding .PP .Vb 1 \& varname = value .Ve .PP lines to the configuration file before using .PP .Vb 1 \& ${varname} .Ve .PP afterwards to recall the assigned values. Here's an example: .PP .Vb 2 \& layout_class = Log::Log4perl::Layout::PatternLayout \& layout_pattern = %d %F{1} %L> %m %n \& \& log4perl.category.Bar.Twix = WARN, Logfile, Screen \& \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.layout = ${layout_class} \& log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern} \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = ${layout_class} \& log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern} .Ve .PP This is a convenient way to define two appenders with the same layout without having to retype the pattern definitions. .PP Variable substitution via \f(CW\*(C`${varname}\*(C'\fR will first try to find an explicitly defined variable. If that fails, it will check your shell's environment for a variable of that name. If that also fails, the program will \f(CW\*(C`die()\*(C'\fR. .SS "Perl Hooks in the Configuration File" .IX Subsection "Perl Hooks in the Configuration File" If some of the values used in the Log4perl configuration file need to be dynamically modified by the program, use Perl hooks: .PP .Vb 2 \& log4perl.appender.File.filename = \e \& sub { return getLogfileName(); } .Ve .PP Each value starting with the string \f(CW\*(C`sub {...\*(C'\fR is interpreted as Perl code to be executed at the time the application parses the configuration via \f(CW\*(C`Log::Log4perl::init()\*(C'\fR. The return value of the subroutine is used by Log::Log4perl as the configuration value. .PP The Perl code is executed in the \f(CW\*(C`main\*(C'\fR package, functions in other packages have to be called in fully-qualified notation. .PP Here's another example, utilizing an environment variable as a username for a \s-1DBI\s0 appender: .PP .Vb 2 \& log4perl.appender.DB.username = \e \& sub { $ENV{DB_USER_NAME } } .Ve .PP However, please note the difference between these code snippets and those used for user-defined conversion specifiers as discussed in Log::Log4perl::Layout::PatternLayout: While the snippets above are run \fIonce\fR when \f(CW\*(C`Log::Log4perl::init()\*(C'\fR is called, the conversion specifier snippets are executed \fIeach time\fR a message is rendered according to the PatternLayout. .PP \&\s-1SECURITY NOTE:\s0 this feature means arbitrary perl code can be embedded in the config file. In the rare case where the people who have access to your config file are different from the people who write your code and shouldn't have execute rights, you might want to set .PP .Vb 1 \& Log::Log4perl::Config\->allow_code(0); .Ve .PP before you call \fIinit()\fR. Alternatively you can supply a restricted set of Perl opcodes that can be embedded in the config file as described in \&\*(L"Restricting what Opcodes can be in a Perl Hook\*(R". .SS "Restricting what Opcodes can be in a Perl Hook" .IX Subsection "Restricting what Opcodes can be in a Perl Hook" The value you pass to Log::Log4perl::Config\->\fIallow_code()\fR determines whether the code that is embedded in the config file is eval'd unrestricted, or eval'd in a Safe compartment. By default, a value of '1' is assumed, which does a normal 'eval' without any restrictions. A value of '0' however prevents any embedded code from being evaluated. .PP If you would like fine-grained control over what can and cannot be included in embedded code, then please utilize the following methods: .PP .Vb 4 \& Log::Log4perl::Config\->allow_code( $allow ); \& Log::Log4perl::Config\->allowed_code_ops($op1, $op2, ... ); \& Log::Log4perl::Config\->vars_shared_with_safe_compartment( [ \e%vars | $package, \e@vars ] ); \& Log::Log4perl::Config\->allowed_code_ops_convenience_map( [ \e%map | $name, \e@mask ] ); .Ve .PP Log::Log4perl::Config\->\fIallowed_code_ops()\fR takes a list of opcode masks that are allowed to run in the compartment. The opcode masks must be specified as described in Opcode: .PP .Vb 1 \& Log::Log4perl::Config\->allowed_code_ops(\*(Aq:subprocess\*(Aq); .Ve .PP This example would allow Perl operations like backticks, system, fork, and waitpid to be executed in the compartment. Of course, you probably don't want to use this mask \*(-- it would allow exactly what the Safe compartment is designed to prevent. .PP Log::Log4perl::Config\->\fIvars_shared_with_safe_compartment()\fR takes the symbols which should be exported into the Safe compartment before the code is evaluated. The keys of this hash are the package names that the symbols are in, and the values are array references to the literal symbol names. For convenience, the default settings export the '%ENV' hash from the 'main' package into the compartment: .PP .Vb 3 \& Log::Log4perl::Config\->vars_shared_with_safe_compartment( \& main => [ \*(Aq%ENV\*(Aq ], \& ); .Ve .PP Log::Log4perl::Config\->\fIallowed_code_ops_convenience_map()\fR is an accessor method to a map of convenience names to opcode masks. At present, the following convenience names are defined: .PP .Vb 2 \& safe = [ \*(Aq:browse\*(Aq ] \& restrictive = [ \*(Aq:default\*(Aq ] .Ve .PP For convenience, if Log::Log4perl::Config\->\fIallow_code()\fR is called with a value which is a key of the map previously defined with Log::Log4perl::Config\->\fIallowed_code_ops_convenience_map()\fR, then the allowed opcodes are set according to the value defined in the map. If this is confusing, consider the following: .PP .Vb 1 \& use Log::Log4perl; \& \& my $config = <<\*(AqEND\*(Aq; \& log4perl.logger = INFO, Main \& log4perl.appender.Main = Log::Log4perl::Appender::File \& log4perl.appender.Main.filename = \e \& sub { "example" . getpwuid($<) . ".log" } \& log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout \& END \& \& $Log::Log4perl::Config\->allow_code(\*(Aqrestrictive\*(Aq); \& Log::Log4perl\->init( \e$config ); # will fail \& $Log::Log4perl::Config\->allow_code(\*(Aqsafe\*(Aq); \& Log::Log4perl\->init( \e$config ); # will succeed .Ve .PP The reason that the first call to \->\fIinit()\fR fails is because the \&'restrictive' name maps to an opcode mask of ':default'. \fIgetpwuid()\fR is not part of ':default', so \->\fIinit()\fR fails. The 'safe' name maps to an opcode mask of ':browse', which allows \fIgetpwuid()\fR to run, so \->\fIinit()\fR succeeds. .PP \&\fIallowed_code_ops_convenience_map()\fR can be invoked in several ways: .IP "\fIallowed_code_ops_convenience_map()\fR" 4 .IX Item "allowed_code_ops_convenience_map()" Returns the entire convenience name map as a hash reference in scalar context or a hash in list context. .IP "allowed_code_ops_convenience_map( \e%map )" 4 .IX Item "allowed_code_ops_convenience_map( %map )" Replaces the entire convenience name map with the supplied hash reference. .ie n .IP "allowed_code_ops_convenience_map( $name )" 4 .el .IP "allowed_code_ops_convenience_map( \f(CW$name\fR )" 4 .IX Item "allowed_code_ops_convenience_map( $name )" Returns the opcode mask for the given convenience name, or undef if no such name is defined in the map. .ie n .IP "allowed_code_ops_convenience_map( $name, \e@mask )" 4 .el .IP "allowed_code_ops_convenience_map( \f(CW$name\fR, \e@mask )" 4 .IX Item "allowed_code_ops_convenience_map( $name, @mask )" Adds the given name/mask pair to the convenience name map. If the name already exists in the map, it's value is replaced with the new mask. .PP as can \fIvars_shared_with_safe_compartment()\fR: .IP "\fIvars_shared_with_safe_compartment()\fR" 4 .IX Item "vars_shared_with_safe_compartment()" Return the entire map of packages to variables as a hash reference in scalar context or a hash in list context. .IP "vars_shared_with_safe_compartment( \e%packages )" 4 .IX Item "vars_shared_with_safe_compartment( %packages )" Replaces the entire map of packages to variables with the supplied hash reference. .ie n .IP "vars_shared_with_safe_compartment( $package )" 4 .el .IP "vars_shared_with_safe_compartment( \f(CW$package\fR )" 4 .IX Item "vars_shared_with_safe_compartment( $package )" Returns the arrayref of variables to be shared for a specific package. .ie n .IP "vars_shared_with_safe_compartment( $package, \e@vars )" 4 .el .IP "vars_shared_with_safe_compartment( \f(CW$package\fR, \e@vars )" 4 .IX Item "vars_shared_with_safe_compartment( $package, @vars )" Adds the given package / varlist pair to the map. If the package already exists in the map, it's value is replaced with the new arrayref of variable names. .PP For more information on opcodes and Safe Compartments, see Opcode and Safe. .SS "Changing the Log Level on a Logger" .IX Subsection "Changing the Log Level on a Logger" Log4perl provides some internal functions for quickly adjusting the log level from within a running Perl program. .PP Now, some people might argue that you should adjust your levels from within an external Log4perl configuration file, but Log4perl is everybody's darling. .PP Typically run-time adjusting of levels is done at the beginning, or in response to some external input (like a \&\*(L"more logging\*(R" runtime command for diagnostics). .PP You get the log level from a logger object with: .PP .Vb 1 \& $current_level = $logger\->level(); .Ve .PP and you may set it with the same method, provided you first imported the log level constants, with: .PP .Vb 1 \& use Log::Log4perl::Level; .Ve .PP Then you can set the level on a logger to one of the constants, .PP .Vb 1 \& $logger\->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL .Ve .PP To \fBincrease\fR the level of logging currently being done, use: .PP .Vb 1 \& $logger\->more_logging($delta); .Ve .PP and to \fBdecrease\fR it, use: .PP .Vb 1 \& $logger\->less_logging($delta); .Ve .PP \&\f(CW$delta\fR must be a positive integer (for now, we may fix this later ;). .PP There are also two equivalent functions: .PP .Vb 2 \& $logger\->inc_level($delta); \& $logger\->dec_level($delta); .Ve .PP They're included to allow you a choice in readability. Some folks will prefer more/less_logging, as they're fairly clear in what they do, and allow the programmer not to worry too much about what a Level is and whether a higher level means more or less logging. However, other folks who do understand and have lots of code that deals with levels will probably prefer the \fIinc_level()\fR and \fIdec_level()\fR methods as they want to work with Levels and not worry about whether that means more or less logging. :) .PP That diatribe aside, typically you'll use \fImore_logging()\fR or \fIinc_level()\fR as such: .PP .Vb 1 \& my $v = 0; # default level of verbosity. \& \& GetOptions("v+" => \e$v, ...); \& \& if( $v ) { \& $logger\->more_logging($v); # inc logging level once for each \-v in ARGV \& } .Ve .SS "Custom Log Levels" .IX Subsection "Custom Log Levels" First off, let me tell you that creating custom levels is heavily deprecated by the log4j folks. Indeed, instead of creating additional levels on top of the predefined \s-1DEBUG, INFO, WARN, ERROR\s0 and \s-1FATAL, \s0 you should use categories to control the amount of logging smartly, based on the location of the log-active code in the system. .PP Nevertheless, Log4perl provides a nice way to create custom levels via the \&\fIcreate_custom_level()\fR routine function. However, this must be done before the first call to \fIinit()\fR or \fIget_logger()\fR. Say you want to create a \s-1NOTIFY\s0 logging level that comes after \s-1WARN \s0(and thus before \s-1INFO\s0). You'd do such as follows: .PP .Vb 2 \& use Log::Log4perl; \& use Log::Log4perl::Level; \& \& Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN"); .Ve .PP And that's it! \f(CW\*(C`create_custom_level()\*(C'\fR creates the following functions / variables for level \s-1FOO:\s0 .PP .Vb 3 \& $FOO_INT # integer to use in L4p::Level::to_level() \& $logger\->foo() # log function to log if level = FOO \& $logger\->is_foo() # true if current level is >= FOO .Ve .PP These levels can also be used in your config file, but note that your config file probably won't be portable to another log4perl or log4j environment unless you've made the appropriate mods there too. .PP Since Log4perl translates log levels to syslog and Log::Dispatch if their appenders are used, you may add mappings for custom levels as well: .PP .Vb 2 \& Log::Log4perl::Level::add_priority("NOTIFY", "WARN", \& $syslog_equiv, $log_dispatch_level); .Ve .PP For example, if your new custom \*(L"\s-1NOTIFY\*(R"\s0 level is supposed to map to syslog level 2 (\*(L"\s-1LOG_NOTICE\*(R"\s0) and Log::Dispatch level 2 (\*(L"notice\*(R"), use: .PP .Vb 1 \& Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN", 2, 2); .Ve .SS "System-wide log levels" .IX Subsection "System-wide log levels" As a fairly drastic measure to decrease (or increase) the logging level all over the system with one single configuration option, use the \f(CW\*(C`threshold\*(C'\fR keyword in the Log4perl configuration file: .PP .Vb 1 \& log4perl.threshold = ERROR .Ve .PP sets the system-wide (or hierarchy-wide according to the log4j documentation) to \s-1ERROR\s0 and therefore deprives every logger in the system of the right to log lower-prio messages. .SS "Easy Mode" .IX Subsection "Easy Mode" For teaching purposes (especially for [1]), I've put \f(CW\*(C`:easy\*(C'\fR mode into \&\f(CW\*(C`Log::Log4perl\*(C'\fR, which just initializes a single root logger with a defined priority and a screen appender including some nice standard layout: .PP .Vb 3 \& ### Initialization Section \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($ERROR); # Set priority of root logger to ERROR \& \& ### Application Section \& my $logger = get_logger(); \& $logger\->fatal("This will get logged."); \& $logger\->debug("This won\*(Aqt."); .Ve .PP This will dump something like .PP .Vb 1 \& 2002/08/04 11:43:09 ERROR> script.pl:16 main::function \- This will get logged. .Ve .PP to the screen. While this has been proven to work well familiarizing people with \f(CW\*(C`Log::Logperl\*(C'\fR slowly, effectively avoiding to clobber them over the head with a plethora of different knobs to fiddle with (categories, appenders, levels, layout), the overall mission of \f(CW\*(C`Log::Log4perl\*(C'\fR is to let people use categories right from the start to get used to the concept. So, let's keep this one fairly hidden in the man page (congrats on reading this far :). .SS "Stealth loggers" .IX Subsection "Stealth loggers" Sometimes, people are lazy. If you're whipping up a 50\-line script and want the comfort of Log::Log4perl without having the burden of carrying a separate log4perl.conf file or a 5\-liner defining that you want to append your log statements to a file, you can use the following features: .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->easy_init( { level => $DEBUG, \& file => ">>test.log" } ); \& \& # Logs to test.log via stealth logger \& DEBUG("Debug this!"); \& INFO("Info this!"); \& WARN("Warn this!"); \& ERROR("Error this!"); \& \& some_function(); \& \& sub some_function { \& # Same here \& FATAL("Fatal this!"); \& } .Ve .PP In \f(CW\*(C`:easy\*(C'\fR mode, \f(CW\*(C`Log::Log4perl\*(C'\fR will instantiate a \fIstealth logger\fR and introduce the convenience functions \f(CW\*(C`TRACE\*(C'\fR, \f(CW\*(C`DEBUG()\*(C'\fR, \f(CW\*(C`INFO()\*(C'\fR, \f(CW\*(C`WARN()\*(C'\fR, \&\f(CW\*(C`ERROR()\*(C'\fR, \f(CW\*(C`FATAL()\*(C'\fR, and \f(CW\*(C`ALWAYS\*(C'\fR into the package namespace. These functions simply take messages as arguments and forward them to the stealth loggers methods (\f(CW\*(C`debug()\*(C'\fR, \&\f(CW\*(C`info()\*(C'\fR, and so on). .PP If a message should never be blocked, regardless of the log level, use the \f(CW\*(C`ALWAYS\*(C'\fR function which corresponds to a log level of \f(CW\*(C`OFF\*(C'\fR: .PP .Vb 1 \& ALWAYS "This will be printed regardless of the log level"; .Ve .PP The \f(CW\*(C`easy_init\*(C'\fR method can be called with a single level value to create a \s-1STDERR\s0 appender and a root logger as in .PP .Vb 1 \& Log::Log4perl\->easy_init($DEBUG); .Ve .PP or, as shown below (and in the example above) with a reference to a hash, specifying values for \f(CW\*(C`level\*(C'\fR (the logger's priority), \f(CW\*(C`file\*(C'\fR (the appender's data sink), \&\f(CW\*(C`category\*(C'\fR (the logger's category and \f(CW\*(C`layout\*(C'\fR for the appender's pattern layout specification. All key-value pairs are optional, they default to \f(CW$DEBUG\fR for \f(CW\*(C`level\*(C'\fR, \f(CW\*(C`STDERR\*(C'\fR for \f(CW\*(C`file\*(C'\fR, \&\f(CW""\fR (root category) for \f(CW\*(C`category\*(C'\fR and \&\f(CW\*(C`%d %m%n\*(C'\fR for \f(CW\*(C`layout\*(C'\fR: .PP .Vb 5 \& Log::Log4perl\->easy_init( { level => $DEBUG, \& file => ">test.log", \& utf8 => 1, \& category => "Bar::Twix", \& layout => \*(Aq%F{1}\-%L\-%M: %m%n\*(Aq } ); .Ve .PP The \f(CW\*(C`file\*(C'\fR parameter takes file names preceded by \f(CW">"\fR (overwrite) and \f(CW">>"\fR (append) as arguments. This will cause \f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR appenders to be created behind the scenes. Also the keywords \f(CW\*(C`STDOUT\*(C'\fR and \f(CW\*(C`STDERR\*(C'\fR (no \f(CW\*(C`>\*(C'\fR or \&\f(CW\*(C`>>\*(C'\fR) are recognized, which will utilize and configure \&\f(CW\*(C`Log::Log4perl::Appender::Screen\*(C'\fR appropriately. The \f(CW\*(C`utf8\*(C'\fR flag, if set to a true value, runs a \f(CW\*(C`binmode\*(C'\fR command on the file handle to establish a utf8 line discipline on the file, otherwise you'll get a \&'wide character in print' warning message and probably not what you'd expect as output. .PP The stealth loggers can be used in different packages, you just need to make sure you're calling the \*(L"use\*(R" function in every package you're using \&\f(CW\*(C`Log::Log4perl\*(C'\fR's easy services: .PP .Vb 3 \& package Bar::Twix; \& use Log::Log4perl qw(:easy); \& sub eat { DEBUG("Twix mjam"); } \& \& package Bar::Mars; \& use Log::Log4perl qw(:easy); \& sub eat { INFO("Mars mjam"); } \& \& package main; \& \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->easy_init( { level => $DEBUG, \& file => ">>test.log", \& category => "Bar::Twix", \& layout => \*(Aq%F{1}\-%L\-%M: %m%n\*(Aq }, \& { level => $DEBUG, \& file => "STDOUT", \& category => "Bar::Mars", \& layout => \*(Aq%m%n\*(Aq }, \& ); \& Bar::Twix::eat(); \& Bar::Mars::eat(); .Ve .PP As shown above, \f(CW\*(C`easy_init()\*(C'\fR will take any number of different logger definitions as hash references. .PP Also, stealth loggers feature the functions \f(CW\*(C`LOGWARN()\*(C'\fR, \f(CW\*(C`LOGDIE()\*(C'\fR, and \f(CW\*(C`LOGEXIT()\*(C'\fR, combining a logging request with a subsequent Perl \fIwarn()\fR or \fIdie()\fR or \fIexit()\fR statement. So, for example .PP .Vb 3 \& if($all_is_lost) { \& LOGDIE("Terrible Problem"); \& } .Ve .PP will log the message if the package's logger is at least \f(CW\*(C`FATAL\*(C'\fR but \&\f(CW\*(C`die()\*(C'\fR (including the traditional output to \s-1STDERR\s0) in any case afterwards. .PP See \*(L"Log and die or warn\*(R" for the similar \f(CW\*(C`logdie()\*(C'\fR and \f(CW\*(C`logwarn()\*(C'\fR functions of regular (i.e non-stealth) loggers. .PP Similarily, \f(CW\*(C`LOGCARP()\*(C'\fR, \f(CW\*(C`LOGCLUCK()\*(C'\fR, \f(CW\*(C`LOGCROAK()\*(C'\fR, and \f(CW\*(C`LOGCONFESS()\*(C'\fR are provided in \f(CW\*(C`:easy\*(C'\fR mode, facilitating the use of \f(CW\*(C`logcarp()\*(C'\fR, \&\f(CW\*(C`logcluck()\*(C'\fR, \f(CW\*(C`logcroak()\*(C'\fR, and \f(CW\*(C`logconfess()\*(C'\fR with stealth loggers. .PP \&\fBWhen using Log::Log4perl in easy mode, please make sure you understand the implications of \&\*(L"Pitfalls with Categories\*(R"\fR. .PP By the way, these convenience functions perform exactly as fast as the standard Log::Log4perl logger methods, there's \fIno\fR performance penalty whatsoever. .SS "Nested Diagnostic Context (\s-1NDC\s0)" .IX Subsection "Nested Diagnostic Context (NDC)" If you find that your application could use a global (thread-specific) data stack which your loggers throughout the system have easy access to, use Nested Diagnostic Contexts (NDCs). Also check out \&\*(L"Mapped Diagnostic Context (\s-1MDC\s0)\*(R", this might turn out to be even more useful. .PP For example, when handling a request of a web client, it's probably useful to have the user's \s-1IP\s0 address available in all log statements within code dealing with this particular request. Instead of passing this piece of data around between your application functions, you can just use the global (but thread-specific) \s-1NDC\s0 mechanism. It allows you to push data pieces (scalars usually) onto its stack via .PP .Vb 2 \& Log::Log4perl::NDC\->push("San"); \& Log::Log4perl::NDC\->push("Francisco"); .Ve .PP and have your loggers retrieve them again via the \*(L"%x\*(R" placeholder in the PatternLayout. With the stack values above and a PatternLayout format like \*(L"%x \f(CW%m\fR%n\*(R", the call .PP .Vb 1 \& $logger\->debug("rocks"); .Ve .PP will end up as .PP .Vb 1 \& San Francisco rocks .Ve .PP in the log appender. .PP The stack mechanism allows for nested structures. Just make sure that at the end of the request, you either decrease the stack one by one by calling .PP .Vb 2 \& Log::Log4perl::NDC\->pop(); \& Log::Log4perl::NDC\->pop(); .Ve .PP or clear out the entire \s-1NDC\s0 stack by calling .PP .Vb 1 \& Log::Log4perl::NDC\->remove(); .Ve .PP Even if you should forget to do that, \f(CW\*(C`Log::Log4perl\*(C'\fR won't grow the stack indefinitely, but limit it to a maximum, defined in \f(CW\*(C`Log::Log4perl::NDC\*(C'\fR (currently 5). A call to \f(CW\*(C`push()\*(C'\fR on a full stack will just replace the topmost element by the new value. .PP Again, the stack is always available via the \*(L"%x\*(R" placeholder in the Log::Log4perl::Layout::PatternLayout class whenever a logger fires. It will replace \*(L"%x\*(R" by the blank-separated list of the values on the stack. It does that by just calling .PP .Vb 1 \& Log::Log4perl::NDC\->get(); .Ve .PP internally. See details on how this standard log4j feature is implemented in Log::Log4perl::NDC. .SS "Mapped Diagnostic Context (\s-1MDC\s0)" .IX Subsection "Mapped Diagnostic Context (MDC)" Just like the previously discussed \s-1NDC\s0 stores thread-specific information in a stack structure, the \s-1MDC\s0 implements a hash table to store key/value pairs in. .PP The static method .PP .Vb 1 \& Log::Log4perl::MDC\->put($key, $value); .Ve .PP stores \f(CW$value\fR under a key \f(CW$key\fR, with which it can be retrieved later (possibly in a totally different part of the system) by calling the \f(CW\*(C`get\*(C'\fR method: .PP .Vb 1 \& my $value = Log::Log4perl::MDC\->get($key); .Ve .PP If no value has been stored previously under \f(CW$key\fR, the \f(CW\*(C`get\*(C'\fR method will return \f(CW\*(C`undef\*(C'\fR. .PP Typically, \s-1MDC\s0 values are retrieved later on via the \f(CW"%X{...}"\fR placeholder in \f(CW\*(C`Log::Log4perl::Layout::PatternLayout\*(C'\fR. If the \f(CW\*(C`get()\*(C'\fR method returns \f(CW\*(C`undef\*(C'\fR, the placeholder will expand to the string \f(CW\*(C`[undef]\*(C'\fR. .PP An application taking a web request might store the remote host like .PP .Vb 1 \& Log::Log4perl::MDC\->put("remote_host", $r\->headers("HOST")); .Ve .PP at its beginning and if the appender's layout looks something like .PP .Vb 1 \& log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n .Ve .PP then a log statement like .PP .Vb 1 \& DEBUG("Content delivered"); .Ve .PP will log something like .PP .Vb 1 \& adsl\-63.dsl.snf.pacbell.net: Content delivered .Ve .PP later on in the program. .PP For details, please check Log::Log4perl::MDC. .SS "Resurrecting hidden Log4perl Statements" .IX Subsection "Resurrecting hidden Log4perl Statements" Sometimes scripts need to be deployed in environments without having Log::Log4perl installed yet. On the other hand, you don't want to live without your Log4perl statements \*(-- they're gonna come in handy later. .PP So, just deploy your script with Log4perl statements commented out with the pattern \f(CW\*(C`###l4p\*(C'\fR, like in .PP .Vb 3 \& ###l4p DEBUG "It works!"; \& # ... \& ###l4p INFO "Really!"; .Ve .PP If Log::Log4perl is available, use the \f(CW\*(C`:resurrect\*(C'\fR tag to have Log4perl resurrect those buried statements before the script starts running: .PP .Vb 1 \& use Log::Log4perl qw(:resurrect :easy); \& \& ###l4p Log::Log4perl\->easy_init($DEBUG); \& ###l4p DEBUG "It works!"; \& # ... \& ###l4p INFO "Really!"; .Ve .PP This will have a source filter kick in and indeed print .PP .Vb 2 \& 2004/11/18 22:08:46 It works! \& 2004/11/18 22:08:46 Really! .Ve .PP In environments lacking Log::Log4perl, just comment out the first line and the script will run nevertheless (but of course without logging): .PP .Vb 1 \& # use Log::Log4perl qw(:resurrect :easy); \& \& ###l4p Log::Log4perl\->easy_init($DEBUG); \& ###l4p DEBUG "It works!"; \& # ... \& ###l4p INFO "Really!"; .Ve .PP because everything's a regular comment now. Alternatively, put the magic Log::Log4perl comment resurrection line into your shell's \&\s-1PERL5OPT\s0 environment variable, e.g. for bash: .PP .Vb 2 \& set PERL5OPT=\-MLog::Log4perl=:resurrect,:easy \& export PERL5OPT .Ve .PP This will awaken the giant within an otherwise silent script like the following: .PP .Vb 1 \& #!/usr/bin/perl \& \& ###l4p Log::Log4perl\->easy_init($DEBUG); \& ###l4p DEBUG "It works!"; .Ve .PP As of \f(CW\*(C`Log::Log4perl\*(C'\fR 1.12, you can even force \fIall\fR modules loaded by a script to have their hidden Log4perl statements resurrected. For this to happen, load \f(CW\*(C`Log::Log4perl::Resurrector\*(C'\fR \&\fIbefore\fR loading any modules: .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& use Log::Log4perl::Resurrector; \& \& use Foobar; # All hidden Log4perl statements in here will \& # be uncommented before Foobar gets loaded. \& \& Log::Log4perl\->easy_init($DEBUG); \& ... .Ve .PP Check the \f(CW\*(C`Log::Log4perl::Resurrector\*(C'\fR manpage for more details. .SS "Access defined appenders" .IX Subsection "Access defined appenders" All appenders defined in the configuration file or via Perl code can be retrieved by the \f(CW\*(C`appender_by_name()\*(C'\fR class method. This comes in handy if you want to manipulate or query appender properties after the Log4perl configuration has been loaded via \f(CW\*(C`init()\*(C'\fR. .PP Note that internally, Log::Log4perl uses the \f(CW\*(C`Log::Log4perl::Appender\*(C'\fR wrapper class to control the real appenders (like \&\f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR or \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR). The \f(CW\*(C`Log::Log4perl::Appender\*(C'\fR class has an \f(CW\*(C`appender\*(C'\fR attribute, pointing to the real appender. .PP The reason for this is that external appenders like \&\f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR don't support all of Log::Log4perl's appender control mechanisms (like appender thresholds). .PP The previously mentioned method \f(CW\*(C`appender_by_name()\*(C'\fR returns a reference to the \fIreal\fR appender object. If you want access to the wrapper class (e.g. if you want to modify the appender's threshold), use the hash \f(CW$Log::Log4perl::Logger::APPENDER_BY_NAME{...}\fR instead, which holds references to all appender wrapper objects. .SS "Modify appender thresholds" .IX Subsection "Modify appender thresholds" To set an appender's threshold, use its \f(CW\*(C`threshold()\*(C'\fR method: .PP .Vb 1 \& $app\->threshold( $FATAL ); .Ve .PP To conveniently adjust \fIall\fR appender thresholds (e.g. because a script uses \fImore_logging()\fR), use .PP .Vb 2 \& # decrease thresholds of all appenders \& Log::Log4perl\->appender_thresholds_adjust(\-1); .Ve .PP This will decrease the thresholds of all appenders in the system by one level, i.e. \s-1WARN\s0 becomes \s-1INFO, INFO\s0 becomes \s-1DEBUG,\s0 etc. To only modify selected ones, use .PP .Vb 2 \& # decrease thresholds of all appenders \& Log::Log4perl\->appender_thresholds_adjust(\-1, [\*(AqAppName1\*(Aq, ...]); .Ve .PP and pass the names of affected appenders in a ref to an array. .SH "Advanced configuration within Perl" .IX Header "Advanced configuration within Perl" Initializing Log::Log4perl can certainly also be done from within Perl. At last, this is what \f(CW\*(C`Log::Log4perl::Config\*(C'\fR does behind the scenes. Log::Log4perl's configuration file parsers are using a publically available \s-1API\s0 to set up Log::Log4perl's categories, appenders and layouts. .PP Here's an example on how to configure two appenders with the same layout in Perl, without using a configuration file at all: .PP .Vb 6 \& ######################## \& # Initialization section \& ######################## \& use Log::Log4perl; \& use Log::Log4perl::Layout; \& use Log::Log4perl::Level; \& \& # Define a category logger \& my $log = Log::Log4perl\->get_logger("Foo::Bar"); \& \& # Define a layout \& my $layout = Log::Log4perl::Layout::PatternLayout\->new("[%r] %F %L %m%n"); \& \& # Define a file appender \& my $file_appender = Log::Log4perl::Appender\->new( \& "Log::Log4perl::Appender::File", \& name => "filelog", \& filename => "/tmp/my.log"); \& \& # Define a stdout appender \& my $stdout_appender = Log::Log4perl::Appender\->new( \& "Log::Log4perl::Appender::Screen", \& name => "screenlog", \& stderr => 0); \& \& # Have both appenders use the same layout (could be different) \& $stdout_appender\->layout($layout); \& $file_appender\->layout($layout); \& \& $log\->add_appender($stdout_appender); \& $log\->add_appender($file_appender); \& $log\->level($INFO); .Ve .PP Please note the class of the appender object is passed as a \fIstring\fR to \&\f(CW\*(C`Log::Log4perl::Appender\*(C'\fR in the \fIfirst\fR argument. Behind the scenes, \&\f(CW\*(C`Log::Log4perl::Appender\*(C'\fR will create the necessary \&\f(CW\*(C`Log::Log4perl::Appender::*\*(C'\fR (or \f(CW\*(C`Log::Dispatch::*\*(C'\fR) object and pass along the name value pairs we provided to \&\f(CW\*(C`Log::Log4perl::Appender\->new()\*(C'\fR after the first argument. .PP The \f(CW\*(C`name\*(C'\fR value is optional and if you don't provide one, \&\f(CW\*(C`Log::Log4perl::Appender\->new()\*(C'\fR will create a unique one for you. The names and values of additional parameters are dependent on the requirements of the particular appender class and can be looked up in their manual pages. .PP A side note: In case you're wondering if \&\f(CW\*(C`Log::Log4perl::Appender\->new()\*(C'\fR will also take care of the \&\f(CW\*(C`min_level\*(C'\fR argument to the \f(CW\*(C`Log::Dispatch::*\*(C'\fR constructors called behind the scenes \*(-- yes, it does. This is because we want the \&\f(CW\*(C`Log::Dispatch\*(C'\fR objects to blindly log everything we send them (\f(CW\*(C`debug\*(C'\fR is their lowest setting) because \fIwe\fR in \f(CW\*(C`Log::Log4perl\*(C'\fR want to call the shots and decide on when and what to log. .PP The call to the appender's \fI\fIlayout()\fI\fR method specifies the format (as a previously created \f(CW\*(C`Log::Log4perl::Layout::PatternLayout\*(C'\fR object) in which the message is being logged in the specified appender. If you don't specify a layout, the logger will fall back to \&\f(CW\*(C`Log::Log4perl::SimpleLayout\*(C'\fR, which logs the debug level, a hyphen (\-) and the log message. .PP Layouts are objects, here's how you create them: .PP .Vb 2 \& # Create a simple layout \& my $simple = Log::Log4perl::SimpleLayout(); \& \& # create a flexible layout: \& # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\en") \& my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n"); .Ve .PP Every appender has exactly one layout assigned to it. You assign the layout to the appender using the appender's \f(CW\*(C`layout()\*(C'\fR object: .PP .Vb 4 \& my $app = Log::Log4perl::Appender\->new( \& "Log::Log4perl::Appender::Screen", \& name => "screenlog", \& stderr => 0); \& \& # Assign the previously defined flexible layout \& $app\->layout($pattern); \& \& # Add the appender to a previously defined logger \& $logger\->add_appender($app); \& \& # ... and you\*(Aqre good to go! \& $logger\->debug("Blah"); \& # => "2002/07/10 23:55:35 (test.pl:207)> Blah\en" .Ve .PP It's also possible to remove appenders from a logger: .PP .Vb 1 \& $logger\->remove_appender($appender_name); .Ve .PP will remove an appender, specified by name, from a given logger. Please note that this does \&\fInot\fR remove an appender from the system. .PP To eradicate an appender from the system, you need to call \f(CW\*(C`Log::Log4perl\->eradicate_appender($appender_name)\*(C'\fR which will first remove the appender from every logger in the system and then will delete all references Log4perl holds to it. .PP To remove a logger from the system, use \&\f(CW\*(C`Log::Log4perl\->remove_logger($logger)\*(C'\fR. After the remaining reference \f(CW$logger\fR goes away, the logger will self-destruct. If the logger in question is a stealth logger, all of its convenience shortcuts (\s-1DEBUG, INFO,\s0 etc) will turn into no-ops. .SH "How about Log::Dispatch::Config?" .IX Header "How about Log::Dispatch::Config?" Tatsuhiko Miyagawa's \f(CW\*(C`Log::Dispatch::Config\*(C'\fR is a very clever simplified logger implementation, covering some of the \fIlog4j\fR functionality. Among the things that \&\f(CW\*(C`Log::Log4perl\*(C'\fR can but \f(CW\*(C`Log::Dispatch::Config\*(C'\fR can't are: .IP "\(bu" 4 You can't assign categories to loggers. For small systems that's fine, but if you can't turn off and on detailed logging in only a tiny subsystem of your environment, you're missing out on a majorly useful log4j feature. .IP "\(bu" 4 Defining appender thresholds. Important if you want to solve problems like "log all messages of level \s-1FATAL\s0 to \s-1STDERR,\s0 plus log all \s-1DEBUG\s0 messages in \f(CW\*(C`Foo::Bar\*(C'\fR to a log file". If you don't have appenders thresholds, there's no way to prevent cluttering \s-1STDERR\s0 with \s-1DEBUG\s0 messages. .IP "\(bu" 4 PatternLayout specifications in accordance with the standard (e.g. \*(L"%d{HH:mm}\*(R"). .PP Bottom line: Log::Dispatch::Config is fine for small systems with simple logging requirements. However, if you're designing a system with lots of subsystems which you need to control independently, you'll love the features of \f(CW\*(C`Log::Log4perl\*(C'\fR, which is equally easy to use. .SH "Using Log::Log4perl with wrapper functions and classes" .IX Header "Using Log::Log4perl with wrapper functions and classes" If you don't use \f(CW\*(C`Log::Log4perl\*(C'\fR as described above, but from a wrapper function, the pattern layout will generate wrong data for \f(CW%F\fR, \f(CW%C\fR, \f(CW%L\fR, and the like. Reason for this is that \f(CW\*(C`Log::Log4perl\*(C'\fR's loggers assume a static caller depth to the application that's using them. .PP If you're using one (or more) wrapper functions, \f(CW\*(C`Log::Log4perl\*(C'\fR will indicate where your logger function called the loggers, not where your application called your wrapper: .PP .Vb 3 \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init({ level => $DEBUG, \& layout => "%M %m%n" }); \& \& sub mylog { \& my($message) = @_; \& \& DEBUG $message; \& } \& \& sub func { \& mylog "Hello"; \& } \& \& func(); .Ve .PP prints .PP .Vb 1 \& main::mylog Hello .Ve .PP but that's probably not what your application expects. Rather, you'd want .PP .Vb 1 \& main::func Hello .Ve .PP because the \f(CW\*(C`func\*(C'\fR function called your logging function. .PP But don't despair, there's a solution: Just register your wrapper package with Log4perl beforehand. If Log4perl then finds that it's being called from a registered wrapper, it will automatically step up to the next call frame. .PP .Vb 1 \& Log::Log4perl\->wrapper_register(_\|_PACKAGE_\|_); \& \& sub mylog { \& my($message) = @_; \& \& DEBUG $message; \& } .Ve .PP Alternatively, you can increase the value of the global variable \&\f(CW$Log::Log4perl::caller_depth\fR (defaults to 0) by one for every wrapper that's in between your application and \f(CW\*(C`Log::Log4perl\*(C'\fR, then \f(CW\*(C`Log::Log4perl\*(C'\fR will compensate for the difference: .PP .Vb 2 \& sub mylog { \& my($message) = @_; \& \& local $Log::Log4perl::caller_depth = \& $Log::Log4perl::caller_depth + 1; \& DEBUG $message; \& } .Ve .PP Also, note that if you're writing a subclass of Log4perl, like .PP .Vb 3 \& package MyL4pWrapper; \& use Log::Log4perl; \& our @ISA = qw(Log::Log4perl); .Ve .PP and you want to call \fIget_logger()\fR in your code, like .PP .Vb 1 \& use MyL4pWrapper; \& \& sub get_logger { \& my $logger = Log::Log4perl\->get_logger(); \& } .Ve .PP then the \fIget_logger()\fR call will get a logger for the \f(CW\*(C`MyL4pWrapper\*(C'\fR category, not for the package calling the wrapper class as in .PP .Vb 2 \& package UserPackage; \& my $logger = MyL4pWrapper\->get_logger(); .Ve .PP To have the above call to get_logger return a logger for the \&\*(L"UserPackage\*(R" category, you need to tell Log4perl that \*(L"MyL4pWrapper\*(R" is a Log4perl wrapper class: .PP .Vb 2 \& use MyL4pWrapper; \& Log::Log4perl\->wrapper_register(_\|_PACKAGE_\|_); \& \& sub get_logger { \& # Now gets a logger for the category of the calling package \& my $logger = Log::Log4perl\->get_logger(); \& } .Ve .PP This feature works both for Log4perl\-relaying classes like the wrapper described above, and for wrappers that inherit from Log4perl use Log4perl's get_logger function via inheritance, alike. .SH "Access to Internals" .IX Header "Access to Internals" The following methods are only of use if you want to peek/poke in the internals of Log::Log4perl. Be careful not to disrupt its inner workings. .ie n .IP """Log::Log4perl\->appenders()""" 4 .el .IP "\f(CWLog::Log4perl\->appenders()\fR" 4 .IX Item "Log::Log4perl->appenders()" To find out which appenders are currently defined (not only for a particular logger, but overall), a \f(CW\*(C`appenders()\*(C'\fR method is available to return a reference to a hash mapping appender names to their Log::Log4perl::Appender object references. .SH "Dirty Tricks" .IX Header "Dirty Tricks" .IP "\fIinfiltrate_lwp()\fR" 4 .IX Item "infiltrate_lwp()" The famous LWP::UserAgent module isn't Log::Log4perl\-enabled. Often, though, especially when tracing Web-related problems, it would be helpful to get some insight on what's happening inside LWP::UserAgent. Ideally, LWP::UserAgent would even play along in the Log::Log4perl framework. .Sp A call to \f(CW\*(C`Log::Log4perl\->infiltrate_lwp()\*(C'\fR does exactly this. In a very rude way, it pulls the rug from under LWP::UserAgent and transforms its \f(CW\*(C`debug/conn\*(C'\fR messages into \f(CW\*(C`debug()\*(C'\fR calls of loggers of the category \&\f(CW"LWP::UserAgent"\fR. Similarily, \f(CW\*(C`LWP::UserAgent\*(C'\fR's \f(CW\*(C`trace\*(C'\fR messages are turned into \f(CW\*(C`Log::Log4perl\*(C'\fR's \f(CW\*(C`info()\*(C'\fR method calls. Note that this only works for LWP::UserAgent versions < 5.822, because this (and probably later) versions miss debugging functions entirely. .IP "Suppressing 'duplicate' \s-1LOGDIE\s0 messages" 4 .IX Item "Suppressing 'duplicate' LOGDIE messages" If a script with a simple Log4perl configuration uses \fIlogdie()\fR to catch errors and stop processing, as in .Sp .Vb 2 \& use Log::Log4perl qw(:easy) ; \& Log::Log4perl\->easy_init($DEBUG); \& \& shaky_function() or LOGDIE "It failed!"; .Ve .Sp there's a cosmetic problem: The message gets printed twice: .Sp .Vb 2 \& 2005/07/10 18:37:14 It failed! \& It failed! at ./t line 12 .Ve .Sp The obvious solution is to use \s-1\fILOGEXIT\s0()\fR instead of \s-1\fILOGDIE\s0()\fR, but there's also a special tag for Log4perl that suppresses the second message: .Sp .Vb 1 \& use Log::Log4perl qw(:no_extra_logdie_message); .Ve .Sp This causes \fIlogdie()\fR and \fIlogcroak()\fR to call \fIexit()\fR instead of \fIdie()\fR. To modify the script exit code in these occasions, set the variable \&\f(CW$Log::Log4perl::LOGEXIT_CODE\fR to the desired value, the default is 1. .IP "Redefine values without causing errors" 4 .IX Item "Redefine values without causing errors" Log4perl's configuration file parser has a few basic safety mechanisms to make sure configurations are more or less sane. .Sp One of these safety measures is catching redefined values. For example, if you first write .Sp .Vb 1 \& log4perl.category = WARN, Logfile .Ve .Sp and then a couple of lines later .Sp .Vb 1 \& log4perl.category = TRACE, Logfile .Ve .Sp then you might have unintentionally overwritten the first value and Log4perl will die on this with an error (suspicious configurations always throw an error). Now, there's a chance that this is intentional, for example when you're lumping together several configuration files and actually \fIwant\fR the first value to overwrite the second. In this case use .Sp .Vb 1 \& use Log::Log4perl qw(:nostrict); .Ve .Sp to put Log4perl in a more permissive mode. .IP "Prevent croak/confess from stringifying" 4 .IX Item "Prevent croak/confess from stringifying" The logcroak/logconfess functions stringify their arguments before they pass them to Carp's croak/confess functions. This can get in the way if you want to throw an object or a hashref as an exception, in this case use: .Sp .Vb 1 \& $Log::Log4perl::STRINGIFY_DIE_MESSAGE = 0; \& \& eval { \& # throws { foo => "bar" } \& # without stringification \& $logger\->logcroak( { foo => "bar" } ); \& }; .Ve .SH "EXAMPLE" .IX Header "EXAMPLE" A simple example to cut-and-paste and get started: .PP .Vb 1 \& use Log::Log4perl qw(get_logger); \& \& my $conf = q( \& log4perl.category.Bar.Twix = WARN, Logfile \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n \& ); \& \& Log::Log4perl::init(\e$conf); \& \& my $logger = get_logger("Bar::Twix"); \& $logger\->error("Blah"); .Ve .PP This will log something like .PP .Vb 1 \& 2002/09/19 23:48:15 t1 25> Blah .Ve .PP to the log file \f(CW\*(C`test.log\*(C'\fR, which Log4perl will append to or create it if it doesn't exist already. .SH "INSTALLATION" .IX Header "INSTALLATION" If you want to use external appenders provided with \f(CW\*(C`Log::Dispatch\*(C'\fR, you need to install \f(CW\*(C`Log::Dispatch\*(C'\fR (2.00 or better) from \s-1CPAN,\s0 which itself depends on \f(CW\*(C`Attribute\-Handlers\*(C'\fR and \&\f(CW\*(C`Params\-Validate\*(C'\fR. And a lot of other modules, that's the reason why we're now shipping Log::Log4perl with its own standard appenders and only if you wish to use additional ones, you'll have to go through the \f(CW\*(C`Log::Dispatch\*(C'\fR installation process. .PP Log::Log4perl needs \f(CW\*(C`Test::More\*(C'\fR, \f(CW\*(C`Test::Harness\*(C'\fR and \f(CW\*(C`File::Spec\*(C'\fR, but they already come with fairly recent versions of perl. If not, everything's automatically fetched from \s-1CPAN\s0 if you're using the \s-1CPAN \s0 shell (\s-1CPAN\s0.pm), because they're listed as dependencies. .PP \&\f(CW\*(C`Time::HiRes\*(C'\fR (1.20 or better) is required only if you need the fine-grained time stamps of the \f(CW%r\fR parameter in \&\f(CW\*(C`Log::Log4perl::Layout::PatternLayout\*(C'\fR. .PP Manual installation works as usual with .PP .Vb 4 \& perl Makefile.PL \& make \& make test \& make install .Ve .SH "DEVELOPMENT" .IX Header "DEVELOPMENT" Log::Log4perl is still being actively developed. We will always make sure the test suite (approx. 500 cases) will pass, but there might still be bugs. please check <http://github.com/mschilli/log4perl> for the latest release. The api has reached a mature state, we will not change it unless for a good reason. .PP Bug reports and feedback are always welcome, just email them to our mailing list shown in the \s-1AUTHORS\s0 section. We're usually addressing them immediately. .SH "REFERENCES" .IX Header "REFERENCES" .IP "[1]" 4 .IX Item "[1]" Michael Schilli, \*(L"Retire your debugger, log smartly with Log::Log4perl!\*(R", Tutorial on perl.com, 09/2002, <http://www.perl.com/pub/a/2002/09/11/log4perl.html> .IP "[2]" 4 .IX Item "[2]" Ceki Gülcü, \*(L"Short introduction to log4j\*(R", <http://logging.apache.org/log4j/1.2/manual.html> .IP "[3]" 4 .IX Item "[3]" Vipan Singla, \*(L"Don't Use System.out.println! Use Log4j.\*(R", <http://www.vipan.com/htdocs/log4jhelp.html> .IP "[4]" 4 .IX Item "[4]" The Log::Log4perl project home page: <http://log4perl.com> .SH "SEE ALSO" .IX Header "SEE ALSO" Log::Log4perl::Config, Log::Log4perl::Appender, Log::Log4perl::Layout::PatternLayout, Log::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level, Log::Log4perl::JavaMap Log::Log4perl::NDC, .SH "AUTHORS" .IX Header "AUTHORS" Please contribute patches to the project on Github: .PP .Vb 1 \& http://github.com/mschilli/log4perl .Ve .PP Send bug reports or requests for enhancements to the authors via our .PP \&\s-1MAILING LIST \s0(questions, bug reports, suggestions/patches): log4perl\-devel@lists.sourceforge.net .PP Authors (please contact them via the list above, not directly): Mike Schilli <m@perlmeister.com>, Kevin Goess <cpan@goess.org> .PP Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier, David Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang. .SH "LICENSE" .IX Header "LICENSE" Copyright 2002\-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess <cpan@goess.org>. .PP This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.