Server IP : 103.119.228.120 / Your IP : 18.222.164.176 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 "FAQ 3" .TH FAQ 3 "2015-04-19" "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::FAQ \- Frequently Asked Questions on Log::Log4perl .SH "DESCRIPTION" .IX Header "DESCRIPTION" This \s-1FAQ\s0 shows a wide variety of commonly encountered logging tasks and how to solve them in the most elegant way with Log::Log4perl. Most of the time, this will be just a matter of smartly configuring your Log::Log4perl configuration files. .SS "Why use Log::Log4perl instead of any other logging module on \s-1CPAN\s0?" .IX Subsection "Why use Log::Log4perl instead of any other logging module on CPAN?" That's a good question. There's dozens of logging modules on \s-1CPAN.\s0 When it comes to logging, people typically think: \*(L"Aha. Writing out debug and error messages. Debug is lower than error. Easy. I'm gonna write my own.\*(R" Writing a logging module is like a rite of passage for every Perl programmer, just like writing your own templating system. .PP Of course, after getting the basics right, features need to be added. You'd like to write a timestamp with every message. Then timestamps with microseconds. Then messages need to be written to both the screen and a log file. .PP And, as your application grows in size you might wonder: Why doesn't my logging system scale along with it? You would like to switch on logging in selected parts of the application, and not all across the board, because this kills performance. This is when people turn to Log::Log4perl, because it handles all of that. .PP Avoid this costly switch. .PP Use \f(CW\*(C`Log::Log4perl\*(C'\fR right from the start. \f(CW\*(C`Log::Log4perl\*(C'\fR's \f(CW\*(C`:easy\*(C'\fR mode supports easy logging in simple scripts: .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); \& \& DEBUG "A low\-level message"; \& ERROR "Won\*(Aqt make it until level gets increased to ERROR"; .Ve .PP And when your application inevitably grows, your logging system grows with it without you having to change any code. .PP Please, don't re-invent logging. \f(CW\*(C`Log::Log4perl\*(C'\fR is here, it's easy to use, it scales, and covers many areas you haven't thought of yet, but will enter soon. .SS "What's the easiest way to use Log4perl?" .IX Subsection "What's the easiest way to use Log4perl?" If you just want to get all the comfort of logging, without much overhead, use \fIStealth Loggers\fR. If you use Log::Log4perl in \&\f(CW\*(C`:easy\*(C'\fR mode like .PP .Vb 1 \& use Log::Log4perl qw(:easy); .Ve .PP you'll have the following functions available in the current package: .PP .Vb 5 \& DEBUG("message"); \& INFO("message"); \& WARN("message"); \& ERROR("message"); \& FATAL("message"); .Ve .PP Just make sure that every package of your code where you're using them in pulls in \f(CW\*(C`use Log::Log4perl qw(:easy)\*(C'\fR first, then you're set. Every stealth logger's category will be equivalent to the name of the package it's located in. .PP These stealth loggers will be absolutely silent until you initialize Log::Log4perl in your main program with either .PP .Vb 2 \& # Define any Log4perl behavior \& Log::Log4perl\->init("foo.conf"); .Ve .PP (using a full-blown Log4perl config file) or the super-easy method .PP .Vb 2 \& # Just log to STDERR \& Log::Log4perl\->easy_init($DEBUG); .Ve .PP or the parameter-style method with a complexity somewhat in between: .PP .Vb 3 \& # Append to a log file \& Log::Log4perl\->easy_init( { level => $DEBUG, \& file => ">>test.log" } ); .Ve .PP For more info, please check out \*(L"Stealth Loggers\*(R" in Log::Log4perl. .SS "How can I simply log all my \s-1ERROR\s0 messages to a file?" .IX Subsection "How can I simply log all my ERROR messages to a file?" After pulling in the \f(CW\*(C`Log::Log4perl\*(C'\fR module, just initialize its behavior by passing in a configuration to its \f(CW\*(C`init\*(C'\fR method as a string reference. Then, obtain a logger instance and write out a message with its \f(CW\*(C`error()\*(C'\fR method: .PP .Vb 1 \& use Log::Log4perl qw(get_logger); \& \& # Define configuration \& my $conf = q( \& log4perl.logger = ERROR, FileApp \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log \& log4perl.appender.FileApp.layout = PatternLayout \& log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n \& ); \& \& # Initialize logging behavior \& Log::Log4perl\->init( \e$conf ); \& \& # Obtain a logger instance \& my $logger = get_logger("Bar::Twix"); \& $logger\->error("Oh my, a dreadful error!"); \& $logger\->warn("Oh my, a dreadful warning!"); .Ve .PP This will append something like .PP .Vb 1 \& 2002/10/29 20:11:55> Oh my, a dreadful error! .Ve .PP to the log file \f(CW\*(C`test.log\*(C'\fR. How does this all work? .PP While the Log::Log4perl \f(CW\*(C`init()\*(C'\fR method typically takes the name of a configuration file as its input parameter like in .PP .Vb 1 \& Log::Log4perl\->init( "/path/mylog.conf" ); .Ve .PP the example above shows how to pass in a configuration as text in a scalar reference. .PP The configuration as shown defines a logger of the root category, which has an appender of type \&\f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR attached. The line .PP .Vb 1 \& log4perl.logger = ERROR, FileApp .Ve .PP doesn't list a category, defining a root logger. Compare that with .PP .Vb 1 \& log4perl.logger.Bar.Twix = ERROR, FileApp .Ve .PP which would define a logger for the category \f(CW\*(C`Bar::Twix\*(C'\fR, showing probably different behavior. \f(CW\*(C`FileApp\*(C'\fR on the right side of the assignment is an arbitrarily defined variable name, which is only used to somehow reference an appender defined later on. .PP Appender settings in the configuration are defined as follows: .PP .Vb 2 \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log .Ve .PP It selects the file appender of the \f(CW\*(C`Log::Log4perl::Appender\*(C'\fR hierarchy, which will append to the file \f(CW\*(C`test.log\*(C'\fR if it already exists. If we wanted to overwrite a potentially existing file, we would have to explicitly set the appropriate \f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR parameter \f(CW\*(C`mode\*(C'\fR: .PP .Vb 3 \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log \& log4perl.appender.FileApp.mode = write .Ve .PP Also, the configuration defines a PatternLayout format, adding the nicely formatted current date and time, an arrow (>) and a space before the messages, which is then followed by a newline: .PP .Vb 2 \& log4perl.appender.FileApp.layout = PatternLayout \& log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n .Ve .PP Obtaining a logger instance and actually logging something is typically done in a different system part as the Log::Log4perl initialisation section, but in this example, it's just done right after init for the sake of compactness: .PP .Vb 3 \& # Obtain a logger instance \& my $logger = get_logger("Bar::Twix"); \& $logger\->error("Oh my, a dreadful error!"); .Ve .PP This retrieves an instance of the logger of the category \f(CW\*(C`Bar::Twix\*(C'\fR, which, as all other categories, inherits behavior from the root logger if no other loggers are defined in the initialization section. .PP The \f(CW\*(C`error()\*(C'\fR method fires up a message, which the root logger catches. Its priority is equal to or higher than the root logger's priority (\s-1ERROR\s0), which causes the root logger to forward it to its attached appender. By contrast, the following .PP .Vb 1 \& $logger\->warn("Oh my, a dreadful warning!"); .Ve .PP doesn't make it through, because the root logger sports a higher setting (\s-1ERROR\s0 and up) than the \s-1WARN\s0 priority of the message. .SS "How can I install Log::Log4perl on Microsoft Windows?" .IX Subsection "How can I install Log::Log4perl on Microsoft Windows?" You can install Log::Log4perl using the \s-1CPAN\s0 client. .PP Alternatively you can install it using .PP .Vb 1 \& ppm install Log\-Log4perl .Ve .PP if you're using ActiveState perl. .PP That's it! Afterwards, just create a Perl script like .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); \& \& my $logger = get_logger("Twix::Bar"); \& $logger\->debug("Watch me!"); .Ve .PP and run it. It should print something like .PP .Vb 1 \& 2002/11/06 01:22:05 Watch me! .Ve .PP If you find that something doesn't work, please let us know at log4perl\-devel@lists.sourceforge.net \*(-- we'll appreciate it. Have fun! .SS "How can I include global (thread-specific) data in my log messages?" .IX Subsection "How can I include global (thread-specific) data in my log messages?" Say, you're writing a web application and want all your log messages to include the current client's \s-1IP\s0 address. Most certainly, you don't want to include it in each and every log message like in .PP .Vb 2 \& $logger\->debug( $r\->connection\->remote_ip, \& " Retrieving user data from DB" ); .Ve .PP do you? Instead, you want to set it in a global data structure and have Log::Log4perl include it automatically via a PatternLayout setting in the configuration file: .PP .Vb 1 \& log4perl.appender.FileApp.layout.ConversionPattern = %X{ip} %m%n .Ve .PP The conversion specifier \f(CW%X{ip}\fR references an entry under the key \&\f(CW\*(C`ip\*(C'\fR in the global \f(CW\*(C`MDC\*(C'\fR (mapped diagnostic context) table, which you've set once via .PP .Vb 1 \& Log::Log4perl::MDC\->put("ip", $r\->connection\->remote_ip); .Ve .PP at the start of the request handler. Note that this is a \&\fIstatic\fR (class) method, there's no logger object involved. You can use this method with as many key/value pairs as you like as long as you reference them under different names. .PP The mappings are stored in a global hash table within Log::Log4perl. Luckily, because the thread model in 5.8.0 doesn't share global variables between threads unless they're explicitly marked as such, there's no problem with multi-threaded environments. .PP For more details on the \s-1MDC,\s0 please refer to \&\*(L"Mapped Diagnostic Context (\s-1MDC\s0)\*(R" in Log::Log4perl and Log::Log4perl::MDC. .SS "My application is already logging to a file. How can I duplicate all messages to also go to the screen?" .IX Subsection "My application is already logging to a file. How can I duplicate all messages to also go to the screen?" Assuming that you already have a Log4perl configuration file like .PP .Vb 1 \& log4perl.logger = DEBUG, FileApp \& \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log \& log4perl.appender.FileApp.layout = PatternLayout \& log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n .Ve .PP and log statements all over your code, it's very easy with Log4perl to have the same messages both printed to the logfile and the screen. No reason to change your code, of course, just add another appender to the configuration file and you're done: .PP .Vb 1 \& log4perl.logger = DEBUG, FileApp, ScreenApp \& \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log \& log4perl.appender.FileApp.layout = PatternLayout \& log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n \& \& log4perl.appender.ScreenApp = Log::Log4perl::Appender::Screen \& log4perl.appender.ScreenApp.stderr = 0 \& log4perl.appender.ScreenApp.layout = PatternLayout \& log4perl.appender.ScreenApp.layout.ConversionPattern = %d> %m%n .Ve .PP The configuration file above is assuming that both appenders are active in the same logger hierarchy, in this case the \f(CW\*(C`root\*(C'\fR category. But even if you've got file loggers defined in several parts of your system, belonging to different logger categories, each logging to different files, you can gobble up all logged messages by defining a root logger with a screen appender, which would duplicate messages from all your file loggers to the screen due to Log4perl's appender inheritance. Check .PP .Vb 1 \& http://www.perl.com/pub/a/2002/09/11/log4perl.html .Ve .PP for details. Have fun! .SS "How can I make sure my application logs a message when it dies unexpectedly?" .IX Subsection "How can I make sure my application logs a message when it dies unexpectedly?" Whenever you encounter a fatal error in your application, instead of saying something like .PP .Vb 1 \& open FILE, "<blah" or die "Can\*(Aqt open blah \-\- bailing out!"; .Ve .PP just use Log::Log4perl's fatal functions instead: .PP .Vb 2 \& my $log = get_logger("Some::Package"); \& open FILE, "<blah" or $log\->logdie("Can\*(Aqt open blah \-\- bailing out!"); .Ve .PP This will both log the message with priority \s-1FATAL\s0 according to your current Log::Log4perl configuration and then call Perl's \f(CW\*(C`die()\*(C'\fR afterwards to terminate the program. It works the same with stealth loggers (see \*(L"Stealth Loggers\*(R" in Log::Log4perl), all you need to do is call .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& open FILE, "<blah" or LOGDIE "Can\*(Aqt open blah \-\- bailing out!"; .Ve .PP What can you do if you're using some library which doesn't use Log::Log4perl and calls \f(CW\*(C`die()\*(C'\fR internally if something goes wrong? Use a \&\f(CW$SIG{_\|_DIE_\|_}\fR pseudo signal handler .PP .Vb 1 \& use Log::Log4perl qw(get_logger); \& \& $SIG{_\|_DIE_\|_} = sub { \& if($^S) { \& # We\*(Aqre in an eval {} and don\*(Aqt want log \& # this message but catch it later \& return; \& } \& local $Log::Log4perl::caller_depth = \& $Log::Log4perl::caller_depth + 1; \& my $logger = get_logger(""); \& $logger\->fatal(@_); \& die @_; # Now terminate really \& }; .Ve .PP This will catch every \f(CW\*(C`die()\*(C'\fR\-Exception of your application or the modules it uses. In case you want to It will fetch a root logger and pass on the \f(CW\*(C`die()\*(C'\fR\-Message to it. If you make sure you've configured with a root logger like this: .PP .Vb 8 \& Log::Log4perl\->init(\eq{ \& log4perl.category = FATAL, Logfile \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.filename = fatal_errors.log \& log4perl.appender.Logfile.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.Logfile.layout.ConversionPattern = %F{1}\-%L (%M)> %m%n \& }); .Ve .PP then all \f(CW\*(C`die()\*(C'\fR messages will be routed to a file properly. The line .PP .Vb 2 \& local $Log::Log4perl::caller_depth = \& $Log::Log4perl::caller_depth + 1; .Ve .PP in the pseudo signal handler above merits a more detailed explanation. With the setup above, if a module calls \f(CW\*(C`die()\*(C'\fR in one of its functions, the fatal message will be logged in the signal handler and not in the original function \*(-- which will cause the \f(CW%F\fR, \f(CW%L\fR and \f(CW%M\fR placeholders in the pattern layout to be replaced by the filename, the line number and the function/method name of the signal handler, not the error-throwing module. To adjust this, Log::Log4perl has the \f(CW$caller_depth\fR variable, which defaults to 0, but can be set to positive integer values to offset the caller level. Increasing it by one will cause it to log the calling function's parameters, not the ones of the signal handler. See \*(L"Using Log::Log4perl from wrapper classes\*(R" in Log::Log4perl for more details. .SS "How can I hook up the \s-1LWP\s0 library with Log::Log4perl?" .IX Subsection "How can I hook up the LWP library with Log::Log4perl?" Or, to put it more generally: How can you utilize a third-party library's embedded logging and debug statements in Log::Log4perl? How can you make them print to configurable appenders, turn them on and off, just as if they were regular Log::Log4perl logging statements? .PP The easiest solution is to map the third-party library logging statements to Log::Log4perl's stealth loggers via a typeglob assignment. .PP As an example, let's take \s-1LWP,\s0 one of the most popular Perl modules, which makes handling \s-1WWW\s0 requests and responses a breeze. Internally, \s-1LWP\s0 uses its own logging and debugging system, utilizing the following calls inside the \s-1LWP\s0 code (from the LWP::Debug man page): .PP .Vb 2 \& # Function tracing \& LWP::Debug::trace(\*(Aqsend()\*(Aq); \& \& # High\-granular state in functions \& LWP::Debug::debug(\*(Aqurl ok\*(Aq); \& \& # Data going over the wire \& LWP::Debug::conns("read $n bytes: $data"); .Ve .PP First, let's assign Log::Log4perl priorities to these functions: I'd suggest that \&\f(CW\*(C`debug()\*(C'\fR messages have priority \f(CW\*(C`INFO\*(C'\fR, \&\f(CW\*(C`trace()\*(C'\fR uses \f(CW\*(C`DEBUG\*(C'\fR and \f(CW\*(C`conns()\*(C'\fR also logs with \f(CW\*(C`DEBUG\*(C'\fR \*(-- although your mileage may certainly vary. .PP Now, in order to transparently hook up LWP::Debug with Log::Log4perl, all we have to do is say .PP .Vb 2 \& package LWP::Debug; \& use Log::Log4perl qw(:easy); \& \& *trace = *INFO; \& *conns = *DEBUG; \& *debug = *DEBUG; \& \& package main; \& # ... go on with your regular program ... .Ve .PP at the beginning of our program. In this way, every time the, say, \&\f(CW\*(C`LWP::UserAgent\*(C'\fR module calls \f(CW\*(C`LWP::Debug::trace()\*(C'\fR, it will implicitly call \s-1\fIINFO\s0()\fR, which is the \f(CW\*(C`info()\*(C'\fR method of a stealth logger defined for the Log::Log4perl category \f(CW\*(C`LWP::Debug\*(C'\fR. Is this cool or what? .PP Here's a complete program: .PP .Vb 3 \& use LWP::UserAgent; \& use HTTP::Request::Common; \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->easy_init( \& { category => "LWP::Debug", \& level => $DEBUG, \& layout => "%r %p %M\-%L %m%n", \& }); \& \& package LWP::Debug; \& use Log::Log4perl qw(:easy); \& *trace = *INFO; \& *conns = *DEBUG; \& *debug = *DEBUG; \& \& package main; \& my $ua = LWP::UserAgent\->new(); \& my $resp = $ua\->request(GET "http://amazon.com"); \& \& if($resp\->is_success()) { \& print "Success: Received ", \& length($resp\->content()), "\en"; \& } else { \& print "Error: ", $resp\->code(), "\en"; \& } .Ve .PP This will generate the following output on \s-1STDERR:\s0 .PP .Vb 10 \& 174 INFO LWP::UserAgent::new\-164 () \& 208 INFO LWP::UserAgent::request\-436 () \& 211 INFO LWP::UserAgent::send_request\-294 GET http://amazon.com \& 212 DEBUG LWP::UserAgent::_need_proxy\-1123 Not proxied \& 405 INFO LWP::Protocol::http::request\-122 () \& 859 DEBUG LWP::Protocol::collect\-206 read 233 bytes \& 863 DEBUG LWP::UserAgent::request\-443 Simple response: Found \& 869 INFO LWP::UserAgent::request\-436 () \& 871 INFO LWP::UserAgent::send_request\-294 \& GET http://www.amazon.com:80/exec/obidos/gateway_redirect \& 872 DEBUG LWP::UserAgent::_need_proxy\-1123 Not proxied \& 873 INFO LWP::Protocol::http::request\-122 () \& 1016 DEBUG LWP::UserAgent::request\-443 Simple response: Found \& 1020 INFO LWP::UserAgent::request\-436 () \& 1022 INFO LWP::UserAgent::send_request\-294 \& GET http://www.amazon.com/exec/obidos/subst/home/home.html/ \& 1023 DEBUG LWP::UserAgent::_need_proxy\-1123 Not proxied \& 1024 INFO LWP::Protocol::http::request\-122 () \& 1382 DEBUG LWP::Protocol::collect\-206 read 632 bytes \& ... \& 2605 DEBUG LWP::Protocol::collect\-206 read 77 bytes \& 2607 DEBUG LWP::UserAgent::request\-443 Simple response: OK \& Success: Received 42584 .Ve .PP Of course, in this way, the embedded logging and debug statements within \&\s-1LWP\s0 can be utilized in any Log::Log4perl way you can think of. You can have them sent to different appenders, block them based on the category and everything else Log::Log4perl has to offer. .PP Only drawback of this method: Steering logging behavior via category is always based on the \f(CW\*(C`LWP::Debug\*(C'\fR package. Although the logging statements reflect the package name of the issuing module properly, the stealth loggers in \f(CW\*(C`LWP::Debug\*(C'\fR are all of the category \f(CW\*(C`LWP::Debug\*(C'\fR. This implies that you can't control the logging behavior based on the package that's \fIinitiating\fR a log request (e.g. LWP::UserAgent) but only based on the package that's actually \fIexecuting\fR the logging statement, \&\f(CW\*(C`LWP::Debug\*(C'\fR in this case. .PP To work around this conundrum, we need to write a wrapper function and plant it into the \f(CW\*(C`LWP::Debug\*(C'\fR package. It will determine the caller and create a logger bound to a category with the same name as the caller's package: .PP .Vb 1 \& package LWP::Debug; \& \& use Log::Log4perl qw(:levels get_logger); \& \& sub l4p_wrapper { \& my($prio, @message) = @_; \& $Log::Log4perl::caller_depth += 2; \& get_logger(scalar caller(1))\->log($prio, @message); \& $Log::Log4perl::caller_depth \-= 2; \& } \& \& no warnings \*(Aqredefine\*(Aq; \& *trace = sub { l4p_wrapper($INFO, @_); }; \& *debug = *conns = sub { l4p_wrapper($DEBUG, @_); }; \& \& package main; \& # ... go on with your main program ... .Ve .PP This is less performant than the previous approach, because every log request will request a reference to a logger first, then call the wrapper, which will in turn call the appropriate log function. .PP This hierarchy shift has to be compensated for by increasing \&\f(CW$Log::Log4perl::caller_depth\fR by 2 before calling the log function and decreasing it by 2 right afterwards. Also, the \f(CW\*(C`l4p_wrapper\*(C'\fR function shown above calls \f(CWcaller(1)\fR which determines the name of the package \fItwo\fR levels down the calling hierarchy (and therefore compensates for both the wrapper function and the anonymous subroutine calling it). .PP \&\f(CW\*(C`no warnings \*(Aqredefine\*(Aq\*(C'\fR suppresses a warning Perl would generate otherwise upon redefining \f(CW\*(C`LWP::Debug\*(C'\fR's \f(CW\*(C`trace()\*(C'\fR, \f(CW\*(C`debug()\*(C'\fR and \f(CW\*(C`conns()\*(C'\fR functions. In case you use a perl prior to 5.6.x, you need to manipulate \f(CW$^W\fR instead. .PP To make things easy for you when dealing with \s-1LWP,\s0 Log::Log4perl 0.47 introduces \f(CW\*(C`Log::Log4perl\->infiltrate_lwp()\*(C'\fR which does exactly the above. .SS "What if I need dynamic values in a static Log4perl configuration file?" .IX Subsection "What if I need dynamic values in a static Log4perl configuration file?" Say, your application uses Log::Log4perl for logging and therefore comes with a Log4perl configuration file, specifying the logging behavior. But, you also want it to take command line parameters to set values like the name of the log file. How can you have both a static Log4perl configuration file and a dynamic command line interface? .PP As of Log::Log4perl 0.28, every value in the configuration file can be specified as a \fIPerl hook\fR. So, instead of saying .PP .Vb 1 \& log4perl.appender.Logfile.filename = test.log .Ve .PP you could just as well have a Perl subroutine deliver the value dynamically: .PP .Vb 1 \& log4perl.appender.Logfile.filename = sub { logfile(); }; .Ve .PP given that \f(CW\*(C`logfile()\*(C'\fR is a valid function in your \f(CW\*(C`main\*(C'\fR package returning a string containing the path to the log file. .PP Or, think about using the value of an environment variable: .PP .Vb 1 \& log4perl.appender.DBI.user = sub { $ENV{USERNAME} }; .Ve .PP When \f(CW\*(C`Log::Log4perl\->init()\*(C'\fR parses the configuration file, it will notice the assignment above because of its \&\f(CW\*(C`sub {...}\*(C'\fR pattern and treat it in a special way: It will evaluate the subroutine (which can contain arbitrary Perl code) and take its return value as the right side of the assignment. .PP A typical application would be called like this on the command line: .PP .Vb 2 \& app # log file is "test.log" \& app \-l mylog.txt # log file is "mylog.txt" .Ve .PP Here's some sample code implementing the command line interface above: .PP .Vb 2 \& use Log::Log4perl qw(get_logger); \& use Getopt::Std; \& \& getopt(\*(Aql:\*(Aq, \eour %OPTS); \& \& my $conf = q( \& log4perl.category.Bar.Twix = WARN, Logfile \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.filename = sub { logfile(); }; \& log4perl.appender.Logfile.layout = SimpleLayout \& ); \& \& Log::Log4perl::init(\e$conf); \& \& my $logger = get_logger("Bar::Twix"); \& $logger\->error("Blah"); \& \& ########################################### \& sub logfile { \& ########################################### \& if(exists $OPTS{l}) { \& return $OPTS{l}; \& } else { \& return "test.log"; \& } \& } .Ve .PP Every Perl hook may contain arbitrary perl code, just make sure to fully qualify eventual variable names (e.g. \f(CW%main::OPTS\fR instead of \f(CW%OPTS\fR). .PP \&\fB\s-1SECURITY NOTE\s0\fR: 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 .PP .Vb 1 \& $Log::Log4perl::Config\->allow_code(0); .Ve .PP before you call \fIinit()\fR. This will prevent Log::Log4perl from executing \fIany\fR Perl code in the config file (including code for custom conversion specifiers (see \*(L"Custom cspecs\*(R" in Log::Log4perl::Layout::PatternLayout). .SS "How can I roll over my logfiles automatically at midnight?" .IX Subsection "How can I roll over my logfiles automatically at midnight?" Long-running applications tend to produce ever-increasing logfiles. For backup and cleanup purposes, however, it is often desirable to move the current logfile to a different location from time to time and start writing a new one. .PP This is a non-trivial task, because it has to happen in sync with the logging system in order not to lose any messages in the process. .PP Luckily, \fIMark Pfeiffer\fR's \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR appender works well with Log::Log4perl to rotate your logfiles in a variety of ways. .PP Note, however, that having the application deal with rotating a log file is not cheap. Among other things, it requires locking the log file with every write to avoid race conditions. There are good reasons to use external rotators like \f(CW\*(C`newsyslog\*(C'\fR instead. See the entry \f(CW\*(C`How can I rotate a logfile with newsyslog?\*(C'\fR in the \&\s-1FAQ\s0 for more information on how to configure it. .PP When using \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR, all you have to do is specify it in your Log::Log4perl configuration file and your logfiles will be rotated automatically. .PP You can choose between rolling based on a maximum size (\*(L"roll if greater than 10 \s-1MB\*(R"\s0) or based on a date pattern (\*(L"roll everyday at midnight\*(R"). In both cases, \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR allows you to define a number \f(CW\*(C`max\*(C'\fR of saved files to keep around until it starts overwriting the oldest ones. If you set the \f(CW\*(C`max\*(C'\fR parameter to 2 and the name of your logfile is \f(CW\*(C`test.log\*(C'\fR, \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR will move \f(CW\*(C`test.log\*(C'\fR to \f(CW\*(C`test.log.1\*(C'\fR on the first rollover. On the second rollover, it will move \f(CW\*(C`test.log.1\*(C'\fR to \f(CW\*(C`test.log.2\*(C'\fR and then \f(CW\*(C`test.log\*(C'\fR to \f(CW\*(C`test.log.1\*(C'\fR. On the third rollover, it will move \f(CW\*(C`test.log.1\*(C'\fR to \&\f(CW\*(C`test.log.2\*(C'\fR (therefore discarding the old \f(CW\*(C`test.log.2\*(C'\fR) and \&\f(CW\*(C`test.log\*(C'\fR to \f(CW\*(C`test.log.1\*(C'\fR. And so forth. This way, there's always going to be a maximum of 2 saved log files around. .PP Here's an example of a Log::Log4perl configuration file, defining a daily rollover at midnight (date pattern \f(CW\*(C`yyyy\-MM\-dd\*(C'\fR), keeping a maximum of 5 saved logfiles around: .PP .Vb 9 \& log4perl.category = WARN, Logfile \& log4perl.appender.Logfile = Log::Dispatch::FileRotate \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.max = 5 \& log4perl.appender.Logfile.DatePattern = yyyy\-MM\-dd \& log4perl.appender.Logfile.TZ = PST \& log4perl.appender.Logfile.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.Logfile.layout.ConversionPattern = %d %m %n .Ve .PP Please see the \f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR documentation for details. \&\f(CW\*(C`Log::Dispatch::FileRotate\*(C'\fR is available on \s-1CPAN.\s0 .SS "What's the easiest way to turn off all logging, even with a lengthy Log4perl configuration file?" .IX Subsection "What's the easiest way to turn off all logging, even with a lengthy Log4perl configuration file?" In addition to category-based levels and appender thresholds, Log::Log4perl supports system-wide logging thresholds. This is the minimum level the system will require of any logging events in order for them to make it through to any configured appenders. .PP For example, putting the line .PP .Vb 1 \& log4perl.threshold = ERROR .Ve .PP anywhere in your configuration file will limit any output to any appender to events with priority of \s-1ERROR\s0 or higher (\s-1ERROR\s0 or \s-1FATAL\s0 that is). .PP However, in order to suppress all logging entirely, you need to use a priority that's higher than \s-1FATAL:\s0 It is simply called \f(CW\*(C`OFF\*(C'\fR, and it is never used by any logger. By definition, it is higher than the highest defined logger level. .PP Therefore, if you keep the line .PP .Vb 1 \& log4perl.threshold = OFF .Ve .PP somewhere in your Log::Log4perl configuration, the system will be quiet as a graveyard. If you deactivate the line (e.g. by commenting it out), the system will, upon config reload, snap back to normal operation, providing logging messages according to the rest of the configuration file again. .SS "How can I log \s-1DEBUG\s0 and above to the screen and \s-1INFO\s0 and above to a file?" .IX Subsection "How can I log DEBUG and above to the screen and INFO and above to a file?" You need one logger with two appenders attached to it: .PP .Vb 1 \& log4perl.logger = DEBUG, Screen, File \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = SimpleLayout \& \& log4perl.appender.File = Log::Log4perl::Appender::File \& log4perl.appender.File.filename = test.log \& log4perl.appender.File.layout = SimpleLayout \& log4perl.appender.Screen.Threshold = INFO .Ve .PP Since the file logger isn't supposed to get any messages with a priority less than \s-1INFO,\s0 the appender's \f(CW\*(C`Threshold\*(C'\fR setting blocks those out, although the logger forwards them. .PP It's a common mistake to think you can define two loggers for this, but it won't work unless those two loggers have different categories. If you wanted to log all \s-1DEBUG\s0 and above messages from the Foo::Bar module to a file and all \s-1INFO\s0 and above messages from the Quack::Schmack module to the screen, then you could have defined two loggers with different levels \&\f(CW\*(C`log4perl.logger.Foo.Bar\*(C'\fR (level \s-1INFO\s0) and \f(CW\*(C`log4perl.logger.Quack.Schmack\*(C'\fR (level \s-1DEBUG\s0) and assigned the file appender to the former and the screen appender to the latter. But what we wanted to accomplish was to route all messages, regardless of which module (or category) they came from, to both appenders. The only way to accomplish this is to define the root logger with the lower level (\s-1DEBUG\s0), assign both appenders to it, and block unwanted messages at the file appender (\f(CW\*(C`Threshold\*(C'\fR set to \s-1INFO\s0). .SS "I keep getting duplicate log messages! What's wrong?" .IX Subsection "I keep getting duplicate log messages! What's wrong?" Having several settings for related categories in the Log4perl configuration file sometimes leads to a phenomenon called \&\*(L"message duplication\*(R". It can be very confusing at first, but if thought through properly, it turns out that Log4perl behaves as advertised. But, don't despair, of course there's a number of ways to avoid message duplication in your logs. .PP Here's a sample Log4perl configuration file that produces the phenomenon: .PP .Vb 2 \& log4perl.logger.Cat = ERROR, Screen \& log4perl.logger.Cat.Subcat = WARN, Screen \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = SimpleLayout .Ve .PP It defines two loggers, one for category \f(CW\*(C`Cat\*(C'\fR and one for \&\f(CW\*(C`Cat::Subcat\*(C'\fR, which is obviously a subcategory of \f(CW\*(C`Cat\*(C'\fR. The parent logger has a priority setting of \s-1ERROR,\s0 the child is set to the lower \f(CW\*(C`WARN\*(C'\fR level. .PP Now imagine the following code in your program: .PP .Vb 2 \& my $logger = get_logger("Cat.Subcat"); \& $logger\->warn("Warning!"); .Ve .PP What do you think will happen? An unexperienced Log4perl user might think: "Well, the message is being sent with level \s-1WARN,\s0 so the \&\f(CW\*(C`Cat::Subcat\*(C'\fR logger will accept it and forward it to the attached \f(CW\*(C`Screen\*(C'\fR appender. Then, the message will percolate up the logger hierarchy, find the \f(CW\*(C`Cat\*(C'\fR logger, which will suppress the message because of its \&\s-1ERROR\s0 setting." But, perhaps surprisingly, what you'll get with the code snippet above is not one but two log messages written to the screen: .PP .Vb 2 \& WARN \- Warning! \& WARN \- Warning! .Ve .PP What happened? The culprit is that once the logger \f(CW\*(C`Cat::Subcat\*(C'\fR decides to fire, it will forward the message \fIunconditionally\fR to all directly or indirectly attached appenders. The \f(CW\*(C`Cat\*(C'\fR logger will never be asked if it wants the message or not \*(-- the message will just be pushed through to the appender attached to \f(CW\*(C`Cat\*(C'\fR. .PP One way to prevent the message from bubbling up the logger hierarchy is to set the \f(CW\*(C`additivity\*(C'\fR flag of the subordinate logger to \&\f(CW0\fR: .PP .Vb 3 \& log4perl.logger.Cat = ERROR, Screen \& log4perl.logger.Cat.Subcat = WARN, Screen \& log4perl.additivity.Cat.Subcat = 0 \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = SimpleLayout .Ve .PP The message will now be accepted by the \f(CW\*(C`Cat::Subcat\*(C'\fR logger, forwarded to its appender, but then \f(CW\*(C`Cat::Subcat\*(C'\fR will suppress any further action. While this setting avoids duplicate messages as seen before, it is often not the desired behavior. Messages percolating up the hierarchy are a useful Log4perl feature. .PP If you're defining \fIdifferent\fR appenders for the two loggers, one other option is to define an appender threshold for the higher-level appender. Typically it is set to be equal to the logger's level setting: .PP .Vb 2 \& log4perl.logger.Cat = ERROR, Screen1 \& log4perl.logger.Cat.Subcat = WARN, Screen2 \& \& log4perl.appender.Screen1 = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen1.layout = SimpleLayout \& log4perl.appender.Screen1.Threshold = ERROR \& \& log4perl.appender.Screen2 = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen2.layout = SimpleLayout .Ve .PP Since the \f(CW\*(C`Screen1\*(C'\fR appender now blocks every message with a priority less than \s-1ERROR,\s0 even if the logger in charge lets it through, the message percolating up the hierarchy is being blocked at the last minute and \fInot\fR appended to \f(CW\*(C`Screen1\*(C'\fR. .PP So far, we've been operating well within the boundaries of the Log4j standard, which Log4perl adheres to. However, if you would really, really like to use a single appender and keep the message percolation intact without having to deal with message duplication, there's a non-standard solution for you: .PP .Vb 2 \& log4perl.logger.Cat = ERROR, Screen \& log4perl.logger.Cat.Subcat = WARN, Screen \& \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = SimpleLayout \& \& log4perl.oneMessagePerAppender = 1 .Ve .PP The \f(CW\*(C`oneMessagePerAppender\*(C'\fR flag will suppress duplicate messages to the same appender. Again, that's non-standard. But way cool :). .SS "How can I configure Log::Log4perl to send me email if something happens?" .IX Subsection "How can I configure Log::Log4perl to send me email if something happens?" Some incidents require immediate action. You can't wait until someone checks the log files, you need to get notified on your pager right away. .PP The easiest way to do that is by using the \f(CW\*(C`Log::Dispatch::Email::MailSend\*(C'\fR module as an appender. It comes with the \f(CW\*(C`Log::Dispatch\*(C'\fR bundle and allows you to specify recipient and subject of outgoing emails in the Log4perl configuration file: .PP .Vb 5 \& log4perl.category = FATAL, Mailer \& log4perl.appender.Mailer = Log::Dispatch::Email::MailSend \& log4perl.appender.Mailer.to = drone@pageme.net \& log4perl.appender.Mailer.subject = Something\*(Aqs broken! \& log4perl.appender.Mailer.layout = SimpleLayout .Ve .PP The message of every log incident this appender gets will then be forwarded to the given email address. Check the \f(CW\*(C`Log::Dispatch::Email::MailSend\*(C'\fR documentation for details. And please make sure there's not a flood of email messages sent out by your application, filling up the recipient's inbox. .PP There's one caveat you need to know about: The \f(CW\*(C`Log::Dispatch::Email\*(C'\fR hierarchy of appenders turns on \fIbuffering\fR by default. This means that the appender will not send out messages right away but wait until a certain threshold has been reached. If you'd rather have your alerts sent out immediately, use .PP .Vb 1 \& log4perl.appender.Mailer.buffered = 0 .Ve .PP to turn buffering off. .SS "How can I write my own appender?" .IX Subsection "How can I write my own appender?" First off, Log::Log4perl comes with a set of standard appenders. Then, there's a lot of Log4perl\-compatible appenders already available on \s-1CPAN:\s0 Just run a search for \f(CW\*(C`Log::Dispatch\*(C'\fR on http://search.cpan.org and chances are that what you're looking for has already been developed, debugged and been used successfully in production \*(-- no need for you to reinvent the wheel. .PP Also, Log::Log4perl ships with a nifty database appender named Log::Log4perl::Appender::DBI \*(-- check it out if talking to databases is your desire. .PP But if you're up for a truly exotic task, you might have to write an appender yourself. That's very easy \*(-- it takes no longer than a couple of minutes. .PP Say, we wanted to create an appender of the class \&\f(CW\*(C`ColorScreenAppender\*(C'\fR, which logs messages to the screen in a configurable color. Just create a new class in \f(CW\*(C`ColorScreenAppender.pm\*(C'\fR: .PP .Vb 1 \& package ColorScreenAppender; .Ve .PP Now let's assume that your Log::Log4perl configuration file \f(CW\*(C`test.conf\*(C'\fR looks like this: .PP .Vb 1 \& log4perl.logger = INFO, ColorApp \& \& log4perl.appender.ColorApp=ColorScreenAppender \& log4perl.appender.ColorApp.color=blue \& \& log4perl.appender.ColorApp.layout = PatternLayout \& log4perl.appender.ColorApp.layout.ConversionPattern=%d %m %n .Ve .PP This will cause Log::Log4perl on \f(CW\*(C`init()\*(C'\fR to look for a class ColorScreenAppender and call its constructor \fInew()\fR. Let's add \&\fInew()\fR to ColorScreenAppender.pm: .PP .Vb 2 \& sub new { \& my($class, %options) = @_; \& \& my $self = { %options }; \& bless $self, $class; \& \& return $self; \& } .Ve .PP To initialize this appender, Log::Log4perl will call and pass all attributes of the appender as defined in the configuration file to the constructor as name/value pairs (in this case just one): .PP .Vb 1 \& ColorScreenAppender\->new(color => "blue"); .Ve .PP The \fInew()\fR method listed above stores the contents of the \&\f(CW%options\fR hash in the object's instance data hash (referred to by \f(CW$self\fR). That's all for initializing a new appender with Log::Log4perl. .PP Second, ColorScreenAppender needs to expose a \&\f(CW\*(C`log()\*(C'\fR method, which will be called by Log::Log4perl every time it thinks the appender should fire. Along with the object reference (as usual in Perl's object world), \fIlog()\fR will receive a list of name/value pairs, of which only the one under the key \f(CW\*(C`message\*(C'\fR shall be of interest for now since it is the message string to be logged. At this point, Log::Log4perl has already taken care of joining the message to be a single string. .PP For our special appender ColorScreenAppender, we're using the Term::ANSIColor module to colorize the output: .PP .Vb 1 \& use Term::ANSIColor; \& \& sub log { \& my($self, %params) = @_; \& \& print colored($params{message}, \& $self\->{color}); \& } .Ve .PP The color (as configured in the Log::Log4perl configuration file) is available as \f(CW$self\fR\->{color} in the appender object. Don't forget to return .PP .Vb 1 \& 1; .Ve .PP at the end of ColorScreenAppender.pm and you're done. Install the new appender somewhere where perl can find it and try it with a test script like .PP .Vb 3 \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->init("test.conf"); \& ERROR("blah"); .Ve .PP to see the new colored output. Is this cool or what? .PP And it gets even better: You can write dynamically generated appender classes using the \f(CW\*(C`Class::Prototyped\*(C'\fR module. Here's an example of an appender prepending every outgoing message with a configurable number of bullets: .PP .Vb 1 \& use Class::Prototyped; \& \& my $class = Class::Prototyped\->newPackage( \& "MyAppenders::Bulletizer", \& bullets => 1, \& log => sub { \& my($self, %params) = @_; \& print "*" x $self\->bullets(), \& $params{message}; \& }, \& ); \& \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->init(\e q{ \& log4perl.logger = INFO, Bully \& \& log4perl.appender.Bully=MyAppenders::Bulletizer \& log4perl.appender.Bully.bullets=3 \& \& log4perl.appender.Bully.layout = PatternLayout \& log4perl.appender.Bully.layout.ConversionPattern=%m %n \& }); \& \& # ... prints: "***Boo!\en"; \& INFO "Boo!"; .Ve .SS "How can I drill down on references before logging them?" .IX Subsection "How can I drill down on references before logging them?" If you've got a reference to a nested structure or object, then you probably don't want to log it as \f(CW\*(C`HASH(0x81141d4)\*(C'\fR but rather dump it as something like .PP .Vb 4 \& $VAR1 = { \& \*(Aqa\*(Aq => \*(Aqb\*(Aq, \& \*(Aqd\*(Aq => \*(Aqe\*(Aq \& }; .Ve .PP via a module like Data::Dumper. While it's syntactically correct to say .PP .Vb 1 \& $logger\->debug(Data::Dumper::Dumper($ref)); .Ve .PP this call imposes a huge performance penalty on your application if the message is suppressed by Log::Log4perl, because Data::Dumper will perform its expensive operations in any case, because it doesn't know that its output will be thrown away immediately. .PP As of Log::Log4perl 0.28, there's a better way: Use the message output filter format as in .PP .Vb 2 \& $logger\->debug( {filter => \e&Data::Dumper::Dumper, \& value => $ref} ); .Ve .PP and Log::Log4perl won't call the filter function unless the message really gets written out to an appender. Just make sure to pass the whole slew as a reference to a hash specifying a filter function (as a sub reference) under the key \f(CW\*(C`filter\*(C'\fR and the value to be passed to the filter function in \&\f(CW\*(C`value\*(C'\fR). When it comes to logging, Log::Log4perl will call the filter function, pass the \f(CW\*(C`value\*(C'\fR as an argument and log the return value. Saves you serious cycles. .SS "How can I collect all \s-1FATAL\s0 messages in an extra log file?" .IX Subsection "How can I collect all FATAL messages in an extra log file?" Suppose you have employed Log4perl all over your system and you've already activated logging in various subsystems. On top of that, without disrupting any other settings, how can you collect all \s-1FATAL\s0 messages all over the system and send them to a separate log file? .PP If you define a root logger like this: .PP .Vb 6 \& log4perl.logger = FATAL, File \& log4perl.appender.File = Log::Log4perl::Appender::File \& log4perl.appender.File.filename = /tmp/fatal.txt \& log4perl.appender.File.layout = PatternLayout \& log4perl.appender.File.layout.ConversionPattern= %d %m %n \& # !!! Something\*(Aqs missing ... .Ve .PP you'll be surprised to not only receive all \s-1FATAL\s0 messages issued anywhere in the system, but also everything else \*(-- gazillions of \&\s-1ERROR, WARN, INFO\s0 and even \s-1DEBUG\s0 messages will end up in your fatal.txt logfile! Reason for this is Log4perl's (or better: Log4j's) appender additivity. Once a lower-level logger decides to fire, the message is going to be forwarded to all appenders upstream \*(-- without further priority checks with their attached loggers. .PP There's a way to prevent this, however: If your appender defines a minimum threshold, only messages of this priority or higher are going to be logged. So, just add .PP .Vb 1 \& log4perl.appender.File.Threshold = FATAL .Ve .PP to the configuration above, and you'll get what you wanted in the first place: An overall system \s-1FATAL\s0 message collector. .SS "How can I bundle several log messages into one?" .IX Subsection "How can I bundle several log messages into one?" Would you like to tally the messages arriving at your appender and dump out a summary once they're exceeding a certain threshold? So that something like .PP .Vb 3 \& $logger\->error("Blah"); \& $logger\->error("Blah"); \& $logger\->error("Blah"); .Ve .PP won't be logged as .PP .Vb 3 \& Blah \& Blah \& Blah .Ve .PP but as .PP .Vb 1 \& [3] Blah .Ve .PP instead? If you'd like to hold off on logging a message until it has been sent a couple of times, you can roll that out by creating a buffered appender. .PP Let's define a new appender like .PP .Vb 1 \& package TallyAppender; \& \& sub new { \& my($class, %options) = @_; \& \& my $self = { maxcount => 5, \& %options \& }; \& \& bless $self, $class; \& \& $self\->{last_message} = ""; \& $self\->{last_message_count} = 0; \& \& return $self; \& } .Ve .PP with two additional instance variables \f(CW\*(C`last_message\*(C'\fR and \&\f(CW\*(C`last_message_count\*(C'\fR, storing the content of the last message sent and a counter of how many times this has happened. Also, it features a configuration parameter \f(CW\*(C`maxcount\*(C'\fR which defaults to 5 in the snippet above but can be set in the Log4perl configuration file like this: .PP .Vb 3 \& log4perl.logger = INFO, A \& log4perl.appender.A=TallyAppender \& log4perl.appender.A.maxcount = 3 .Ve .PP The main tallying logic lies in the appender's \f(CW\*(C`log\*(C'\fR method, which is called every time Log4perl thinks a message needs to get logged by our appender: .PP .Vb 2 \& sub log { \& my($self, %params) = @_; \& \& # Message changed? Print buffer. \& if($self\->{last_message} and \& $params{message} ne $self\->{last_message}) { \& print "[$self\->{last_message_count}]: " . \& "$self\->{last_message}"; \& $self\->{last_message_count} = 1; \& $self\->{last_message} = $params{message}; \& return; \& } \& \& $self\->{last_message_count}++; \& $self\->{last_message} = $params{message}; \& \& # Threshold exceeded? Print, reset counter \& if($self\->{last_message_count} >= \& $self\->{maxcount}) { \& print "[$self\->{last_message_count}]: " . \& "$params{message}"; \& $self\->{last_message_count} = 0; \& $self\->{last_message} = ""; \& return; \& } \& } .Ve .PP We basically just check if the oncoming message in \f(CW$param{message}\fR is equal to what we've saved before in the \f(CW\*(C`last_message\*(C'\fR instance variable. If so, we're increasing \f(CW\*(C`last_message_count\*(C'\fR. We print the message in two cases: If the new message is different than the buffered one, because then we need to dump the old stuff and store the new. Or, if the counter exceeds the threshold, as defined by the \f(CW\*(C`maxcount\*(C'\fR configuration parameter. .PP Please note that the appender always gets the fully rendered message and just compares it as a whole \*(-- so if there's a date/timestamp in there, that might confuse your logic. You can work around this by specifying \&\f(CW%m\fR \f(CW%n\fR as a layout and add the date later on in the appender. Or, make the comparison smart enough to omit the date. .PP At last, don't forget what happens if the program is being shut down. If there's still messages in the buffer, they should be printed out at that point. That's easy to do in the appender's \s-1DESTROY\s0 method, which gets called at object destruction time: .PP .Vb 2 \& sub DESTROY { \& my($self) = @_; \& \& if($self\->{last_message_count}) { \& print "[$self\->{last_message_count}]: " . \& "$self\->{last_message}"; \& return; \& } \& } .Ve .PP This will ensure that none of the buffered messages are lost. Happy buffering! .SS "I want to log \s-1ERROR\s0 and \s-1WARN\s0 messages to different files! How can I do that?" .IX Subsection "I want to log ERROR and WARN messages to different files! How can I do that?" Let's assume you wanted to have each logging statement written to a different file, based on the statement's priority. Messages with priority \&\f(CW\*(C`WARN\*(C'\fR are supposed to go to \f(CW\*(C`/tmp/app.warn\*(C'\fR, events prioritized as \f(CW\*(C`ERROR\*(C'\fR should end up in \f(CW\*(C`/tmp/app.error\*(C'\fR. .PP Now, if you define two appenders \f(CW\*(C`AppWarn\*(C'\fR and \f(CW\*(C`AppError\*(C'\fR and assign them both to the root logger, messages bubbling up from any loggers below will be logged by both appenders because of Log4perl's message propagation feature. If you limit their exposure via the appender threshold mechanism and set \&\f(CW\*(C`AppWarn\*(C'\fR's threshold to \f(CW\*(C`WARN\*(C'\fR and \f(CW\*(C`AppError\*(C'\fR's to \f(CW\*(C`ERROR\*(C'\fR, you'll still get \f(CW\*(C`ERROR\*(C'\fR messages in \f(CW\*(C`AppWarn\*(C'\fR, because \f(CW\*(C`AppWarn\*(C'\fR's \f(CW\*(C`WARN\*(C'\fR setting will just filter out messages with a \fIlower\fR priority than \&\f(CW\*(C`WARN\*(C'\fR \*(-- \f(CW\*(C`ERROR\*(C'\fR is higher and will be allowed to pass through. .PP What we need for this is a Log4perl \fICustom Filter\fR, available with Log::Log4perl 0.30. .PP Both appenders need to verify that the priority of the oncoming messages exactly \fImatches\fR the priority the appender is supposed to log messages of. To accomplish this task, let's define two custom filters, \f(CW\*(C`MatchError\*(C'\fR and \f(CW\*(C`MatchWarn\*(C'\fR, which, when attached to their appenders, will limit messages passed on to them to those matching a given priority: .PP .Vb 1 \& log4perl.logger = WARN, AppWarn, AppError \& \& # Filter to match level ERROR \& log4perl.filter.MatchError = Log::Log4perl::Filter::LevelMatch \& log4perl.filter.MatchError.LevelToMatch = ERROR \& log4perl.filter.MatchError.AcceptOnMatch = true \& \& # Filter to match level WARN \& log4perl.filter.MatchWarn = Log::Log4perl::Filter::LevelMatch \& log4perl.filter.MatchWarn.LevelToMatch = WARN \& log4perl.filter.MatchWarn.AcceptOnMatch = true \& \& # Error appender \& log4perl.appender.AppError = Log::Log4perl::Appender::File \& log4perl.appender.AppError.filename = /tmp/app.err \& log4perl.appender.AppError.layout = SimpleLayout \& log4perl.appender.AppError.Filter = MatchError \& \& # Warning appender \& log4perl.appender.AppWarn = Log::Log4perl::Appender::File \& log4perl.appender.AppWarn.filename = /tmp/app.warn \& log4perl.appender.AppWarn.layout = SimpleLayout \& log4perl.appender.AppWarn.Filter = MatchWarn .Ve .PP The appenders \f(CW\*(C`AppWarn\*(C'\fR and \f(CW\*(C`AppError\*(C'\fR defined above are logging to \f(CW\*(C`/tmp/app.warn\*(C'\fR and \&\f(CW\*(C`/tmp/app.err\*(C'\fR respectively and have the custom filters \f(CW\*(C`MatchWarn\*(C'\fR and \f(CW\*(C`MatchError\*(C'\fR attached. This setup will direct all \s-1WARN\s0 messages, issued anywhere in the system, to /tmp/app.warn (and \&\s-1ERROR\s0 messages to /tmp/app.error) \*(-- without any overlaps. .SS "On our server farm, Log::Log4perl configuration files differ slightly from host to host. Can I roll them all into one?" .IX Subsection "On our server farm, Log::Log4perl configuration files differ slightly from host to host. Can I roll them all into one?" You sure can, because Log::Log4perl allows you to specify attribute values dynamically. Let's say that one of your appenders expects the host's \s-1IP\s0 address as one of its attributes. Now, you could certainly roll out different configuration files for every host and specify the value like .PP .Vb 2 \& log4perl.appender.MyAppender = Log::Log4perl::Appender::SomeAppender \& log4perl.appender.MyAppender.ip = 10.0.0.127 .Ve .PP but that's a maintenance nightmare. Instead, you can have Log::Log4perl figure out the \s-1IP\s0 address at configuration time and set the appender's value correctly: .PP .Vb 7 \& # Set the IP address dynamically \& log4perl.appender.MyAppender = Log::Log4perl::Appender::SomeAppender \& log4perl.appender.MyAppender.ip = sub { \e \& use Sys::Hostname; \e \& use Socket; \e \& return inet_ntoa(scalar gethostbyname hostname); \e \& } .Ve .PP If Log::Log4perl detects that an attribute value starts with something like \&\f(CW"sub {..."\fR, it will interpret it as a perl subroutine which is to be executed once at configuration time (not runtime!) and its return value is to be used as the attribute value. This comes in handy for rolling out applications where Log::Log4perl configuration files show small host-specific differences, because you can deploy the unmodified application distribution on all instances of the server farm. .SS "Log4perl doesn't interpret my backslashes correctly!" .IX Subsection "Log4perl doesn't interpret my backslashes correctly!" If you're using Log4perl's feature to specify the configuration as a string in your program (as opposed to a separate configuration file), chances are that you've written it like this: .PP .Vb 1 \& # *** WRONG! *** \& \& Log::Log4perl\->init( \e <<END_HERE); \& log4perl.logger = WARN, A1 \& log4perl.appender.A1 = Log::Log4perl::Appender::Screen \& log4perl.appender.A1.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.A1.layout.ConversionPattern = %m%n \& END_HERE \& \& # *** WRONG! *** .Ve .PP and you're getting the following error message: .PP .Vb 1 \& Layout not specified for appender A1 at .../Config.pm line 342. .Ve .PP What's wrong? The problem is that you're using a here-document with substitution enabled (\f(CW\*(C`<<END_HERE\*(C'\fR) and that Perl won't interpret backslashes at line-ends as continuation characters but will essentially throw them out. So, in the code above, the layout line will look like .PP .Vb 1 \& log4perl.appender.A1.layout = .Ve .PP to Log::Log4perl which causes it to report an error. To interpret the backslash at the end of the line correctly as a line-continuation character, use the non-interpreting mode of the here-document like in .PP .Vb 1 \& # *** RIGHT! *** \& \& Log::Log4perl\->init( \e <<\*(AqEND_HERE\*(Aq); \& log4perl.logger = WARN, A1 \& log4perl.appender.A1 = Log::Log4perl::Appender::Screen \& log4perl.appender.A1.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.A1.layout.ConversionPattern = %m%n \& END_HERE \& \& # *** RIGHT! *** .Ve .PP (note the single quotes around \f(CW\*(AqEND_HERE\*(Aq\fR) or use \f(CW\*(C`q{...}\*(C'\fR instead of a here-document and Perl will treat the backslashes at line-end as intended. .SS "I want to suppress certain messages based on their content!" .IX Subsection "I want to suppress certain messages based on their content!" Let's assume you've plastered all your functions with Log4perl statements like .PP .Vb 1 \& sub some_func { \& \& INFO("Begin of function"); \& \& # ... Stuff happens here ... \& \& INFO("End of function"); \& } .Ve .PP to issue two log messages, one at the beginning and one at the end of each function. Now you want to suppress the message at the beginning and only keep the one at the end, what can you do? You can't use the category mechanism, because both messages are issued from the same package. .PP Log::Log4perl's custom filters (0.30 or better) provide an interface for the Log4perl user to step in right before a message gets logged and decide if it should be written out or suppressed, based on the message content or other parameters: .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl::init( \e <<\*(AqEOT\*(Aq ); \& log4perl.logger = INFO, A1 \& log4perl.appender.A1 = Log::Log4perl::Appender::Screen \& log4perl.appender.A1.layout = \e \& Log::Log4perl::Layout::PatternLayout \& log4perl.appender.A1.layout.ConversionPattern = %m%n \& \& log4perl.filter.M1 = Log::Log4perl::Filter::StringMatch \& log4perl.filter.M1.StringToMatch = Begin \& log4perl.filter.M1.AcceptOnMatch = false \& \& log4perl.appender.A1.Filter = M1 \&EOT .Ve .PP The last four statements in the configuration above are defining a custom filter \f(CW\*(C`M1\*(C'\fR of type \f(CW\*(C`Log::Log4perl::Filter::StringMatch\*(C'\fR, which comes with Log4perl right out of the box and allows you to define a text pattern to match (as a perl regular expression) and a flag \f(CW\*(C`AcceptOnMatch\*(C'\fR indicating if a match is supposed to suppress the message or let it pass through. .PP The last line then assigns this filter to the \f(CW\*(C`A1\*(C'\fR appender, which will call it every time it receives a message to be logged and throw all messages out \fInot\fR matching the regular expression \f(CW\*(C`Begin\*(C'\fR. .PP Instead of using the standard \f(CW\*(C`Log::Log4perl::Filter::StringMatch\*(C'\fR filter, you can define your own, simply using a perl subroutine: .PP .Vb 2 \& log4perl.filter.ExcludeBegin = sub { !/Begin/ } \& log4perl.appender.A1.Filter = ExcludeBegin .Ve .PP For details on custom filters, check Log::Log4perl::Filter. .SS "My new module uses Log4perl \*(-- but what happens if the calling program didn't configure it?" .IX Subsection "My new module uses Log4perl but what happens if the calling program didn't configure it?" If a Perl module uses Log::Log4perl, it will typically rely on the calling program to initialize it. If it is using Log::Log4perl in \f(CW\*(C`:easy\*(C'\fR mode, like in .PP .Vb 2 \& package MyMod; \& use Log::Log4perl qw(:easy); \& \& sub foo { \& DEBUG("In foo"); \& } \& \& 1; .Ve .PP and the calling program doesn't initialize Log::Log4perl at all (e.g. because it has no clue that it's available), Log::Log4perl will silently ignore all logging messages. However, if the module is using Log::Log4perl in regular mode like in .PP .Vb 2 \& package MyMod; \& use Log::Log4perl qw(get_logger); \& \& sub foo { \& my $logger = get_logger(""); \& $logger\->debug("blah"); \& } \& \& 1; .Ve .PP and the main program is just using the module like in .PP .Vb 2 \& use MyMode; \& MyMode::foo(); .Ve .PP then Log::Log4perl will also ignore all logging messages but issue a warning like .PP .Vb 2 \& Log4perl: Seems like no initialization happened. \& Forgot to call init()? .Ve .PP (only once!) to remind novice users to not forget to initialize the logging system before using it. However, if you want to suppress this message, just add the \f(CW\*(C`:nowarn\*(C'\fR target to the module's \f(CW\*(C`use Log::Log4perl\*(C'\fR call: .PP .Vb 1 \& use Log::Log4perl qw(get_logger :nowarn); .Ve .PP This will have Log::Log4perl silently ignore all logging statements if no initialization has taken place. If, instead of using \fIinit()\fR, you're using Log4perl's \s-1API\s0 to define loggers and appenders, the same notification happens if no call to \fIadd_appenders()\fR is made, i.e. no appenders are defined. .PP If the module wants to figure out if some other program part has already initialized Log::Log4perl, it can do so by calling .PP .Vb 1 \& Log::Log4perl::initialized() .Ve .PP which will return a true value in case Log::Log4perl has been initialized and a false value if not. .SS "How can I synchronize access to an appender?" .IX Subsection "How can I synchronize access to an appender?" If you're using the same instance of an appender in multiple processes, and each process is passing on messages to the appender in parallel, you might end up with overlapping log entries. .PP Typical scenarios include a file appender that you create in the main program, and which will then be shared between the parent and a forked child process. Or two separate processes, each initializing a Log4perl file appender on the same logfile. .PP Log::Log4perl won't synchronize access to the shared logfile by default. Depending on your operating system's flush mechanism, buffer size and the size of your messages, there's a small chance of an overlap. .PP The easiest way to prevent overlapping messages in logfiles written to by multiple processes is setting the file appender's \f(CW\*(C`syswrite\*(C'\fR flag along with a file write mode of \f(CW"append"\fR. This makes sure that \&\f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR uses \f(CW\*(C`syswrite()\*(C'\fR (which is guaranteed to run uninterrupted) instead of \f(CW\*(C`print()\*(C'\fR which might buffer the message or get interrupted by the \s-1OS\s0 while it is writing. And in \&\f(CW"append"\fR mode, the \s-1OS\s0 kernel ensures that multiple processes share one end-of-file marker, ensuring that each process writes to the \fIreal\fR end of the file. (The value of \f(CW"append"\fR for the \f(CW\*(C`mode\*(C'\fR parameter is the default setting in Log4perl's file appender so you don't have to set it explicitly.) .PP .Vb 1 \& # Guarantees atomic writes \& \& log4perl.category.Bar.Twix = WARN, Logfile \& \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.mode = append \& log4perl.appender.Logfile.syswrite = 1 \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.layout = SimpleLayout .Ve .PP Another guaranteed way of having messages separated with any kind of appender is putting a Log::Log4perl::Appender::Synchronized composite appender in between Log::Log4perl and the real appender. It will make sure to let messages pass through this virtual gate one by one only. .PP Here's a sample configuration to synchronize access to a file appender: .PP .Vb 1 \& log4perl.category.Bar.Twix = WARN, Syncer \& \& log4perl.appender.Logfile = Log::Log4perl::Appender::File \& log4perl.appender.Logfile.autoflush = 1 \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.layout = SimpleLayout \& \& log4perl.appender.Syncer = Log::Log4perl::Appender::Synchronized \& log4perl.appender.Syncer.appender = Logfile .Ve .PP \&\f(CW\*(C`Log::Log4perl::Appender::Synchronized\*(C'\fR uses the \f(CW\*(C`IPC::Shareable\*(C'\fR module and its semaphores, which will slow down writing the log messages, but ensures sequential access featuring atomic checks. Check Log::Log4perl::Appender::Synchronized for details. .SS "Can I use Log::Log4perl with log4j's Chainsaw?" .IX Subsection "Can I use Log::Log4perl with log4j's Chainsaw?" Yes, Log::Log4perl can be configured to send its events to log4j's graphical log \s-1UI \s0\fIChainsaw\fR. .PP Here's how it works: .IP "\(bu" 4 Get Guido Carls' <gcarls@cpan.org> Log::Log4perl extension \&\f(CW\*(C`Log::Log4perl::Layout::XMLLayout\*(C'\fR from \s-1CPAN\s0 and install it: .Sp .Vb 2 \& perl \-MCPAN \-eshell \& cpan> install Log::Log4perl::Layout::XMLLayout .Ve .IP "\(bu" 4 Install and start Chainsaw, which is part of the \f(CW\*(C`log4j\*(C'\fR distribution now (see http://jakarta.apache.org/log4j ). Create a configuration file like .Sp .Vb 8 \& <log4j:configuration debug="true"> \& <plugin name="XMLSocketReceiver" \& class="org.apache.log4j.net.XMLSocketReceiver"> \& <param name="decoder" value="org.apache.log4j.xml.XMLDecoder"/> \& <param name="Port" value="4445"/> \& </plugin> \& <root> <level value="debug"/> </root> \& </log4j:configuration> .Ve .Sp and name it e.g. \f(CW\*(C`config.xml\*(C'\fR. Then start Chainsaw like .Sp .Vb 3 \& java \-Dlog4j.debug=true \-Dlog4j.configuration=config.xml \e \& \-classpath ".:log4j\-1.3alpha.jar:log4j\-chainsaw\-1.3alpha.jar" \e \& org.apache.log4j.chainsaw.LogUI .Ve .Sp and watch the \s-1GUI\s0 coming up. .IP "\(bu" 4 Configure Log::Log4perl to use a socket appender with an XMLLayout, pointing to the host/port where Chainsaw (as configured above) is waiting with its XMLSocketReceiver: .Sp .Vb 2 \& use Log::Log4perl qw(get_logger); \& use Log::Log4perl::Layout::XMLLayout; \& \& my $conf = q( \& log4perl.category.Bar.Twix = WARN, Appender \& log4perl.appender.Appender = Log::Log4perl::Appender::Socket \& log4perl.appender.Appender.PeerAddr = localhost \& log4perl.appender.Appender.PeerPort = 4445 \& log4perl.appender.Appender.layout = Log::Log4perl::Layout::XMLLayout \& ); \& \& Log::Log4perl::init(\e$conf); \& \& # Nasty hack to suppress encoding header \& my $app = Log::Log4perl::appenders\->{"Appender"}; \& $app\->layout()\->{enc_set} = 1; \& \& my $logger = get_logger("Bar.Twix"); \& $logger\->error("One"); .Ve .Sp The nasty hack shown in the code snippet above is currently (October 2003) necessary, because Chainsaw expects \s-1XML\s0 messages to arrive in a format like .Sp .Vb 12 \& <log4j:event logger="Bar.Twix" \& timestamp="1066794904310" \& level="ERROR" \& thread="10567"> \& <log4j:message><![CDATA[Two]]></log4j:message> \& <log4j:NDC><![CDATA[undef]]></log4j:NDC> \& <log4j:locationInfo class="main" \& method="main" \& file="./t" \& line="32"> \& </log4j:locationInfo> \& </log4j:event> .Ve .Sp without a preceding .Sp .Vb 1 \& <?xml version = "1.0" encoding = "iso8859\-1"?> .Ve .Sp which Log::Log4perl::Layout::XMLLayout applies to the first event sent over the socket. .PP See figure 1 for a screenshot of Chainsaw in action, receiving events from the Perl script shown above. .PP Many thanks to Chainsaw's Scott Deboy <sdeboy@comotivsystems.com> for his support! .SS "How can I run Log::Log4perl under mod_perl?" .IX Subsection "How can I run Log::Log4perl under mod_perl?" In persistent environments it's important to play by the rules outlined in section \*(L"Initialize once and only once\*(R" in Log::Log4perl. If you haven't read this yet, please go ahead and read it right now. It's very important. .PP And no matter if you use a startup handler to \fIinit()\fR Log::Log4perl or use the \&\fIinit_once()\fR strategy (added in 0.42), either way you're very likely to have unsynchronized writes to logfiles. .PP If Log::Log4perl is configured with a log file appender, and it is initialized via the Apache startup handler, the file handle created initially will be shared among all Apache processes. Similarly, with the \fIinit_once()\fR approach: although every process has a separate L4p configuration, processes are gonna share the appender file \fInames\fR instead, effectively opening several different file handles on the same file. .PP Now, having several appenders using the same file handle or having several appenders logging to the same file unsynchronized, this might result in overlapping messages. Sometimes, this is acceptable. If it's not, here's two strategies: .IP "\(bu" 4 Use the Log::Log4perl::Appender::Synchronized appender to connect to your file appenders. Here's the writeup: http://log4perl.sourceforge.net/releases/Log\-Log4perl/docs/html/Log/Log4perl/FAQ.html#23804 .IP "\(bu" 4 Use a different logfile for every process like in .Sp .Vb 3 \& #log4perl.conf \& ... \& log4perl.appender.A1.filename = sub { "mylog.$$.log" } .Ve .SS "My program already uses \fIwarn()\fP and \fIdie()\fP. How can I switch to Log4perl?" .IX Subsection "My program already uses warn() and die(). How can I switch to Log4perl?" If your program already uses Perl's \f(CW\*(C`warn()\*(C'\fR function to spew out error messages and you'd like to channel those into the Log4perl world, just define a \f(CW\*(C`_\|_WARN_\|_\*(C'\fR handler where your program or module resides: .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& $SIG{_\|_WARN_\|_} = sub { \& local $Log::Log4perl::caller_depth = \& $Log::Log4perl::caller_depth + 1; \& WARN @_; \& }; .Ve .PP Why the \f(CW\*(C`local\*(C'\fR setting of \f(CW$Log::Log4perl::caller_depth\fR? If you leave that out, \&\f(CW\*(C`PatternLayout\*(C'\fR conversion specifiers like \f(CW%M\fR or \f(CW%F\fR (printing the current function/method and source filename) will refer to where the _\|_WARN_\|_ handler resides, not the environment Perl's \f(CW\*(C`warn()\*(C'\fR function was issued from. Increasing \f(CW\*(C`caller_depth\*(C'\fR adjusts for this offset. Having it \f(CW\*(C`local\*(C'\fR, makes sure the level gets set back after the handler exits. .PP Once done, if your program does something like .PP .Vb 3 \& sub some_func { \& warn "Here\*(Aqs a warning"; \& } .Ve .PP you'll get (depending on your Log::Log4perl configuration) something like .PP .Vb 1 \& 2004/02/19 20:41:02\-main::some_func: Here\*(Aqs a warning at ./t line 25. .Ve .PP in the appropriate appender instead of having a screen full of \s-1STDERR\s0 messages. It also works with the \f(CW\*(C`Carp\*(C'\fR module and its \f(CW\*(C`carp()\*(C'\fR and \f(CW\*(C`cluck()\*(C'\fR functions. .PP If, on the other hand, catching \f(CW\*(C`die()\*(C'\fR and friends is required, a \f(CW\*(C`_\|_DIE_\|_\*(C'\fR handler is appropriate: .PP .Vb 10 \& $SIG{_\|_DIE_\|_} = sub { \& if($^S) { \& # We\*(Aqre in an eval {} and don\*(Aqt want log \& # this message but catch it later \& return; \& } \& local $Log::Log4perl::caller_depth = \& $Log::Log4perl::caller_depth + 1; \& LOGDIE @_; \& }; .Ve .PP This will call Log4perl's \f(CW\*(C`LOGDIE()\*(C'\fR function, which will log a fatal error and then call \fIdie()\fR internally, causing the program to exit. Works equally well with \f(CW\*(C`Carp\*(C'\fR's \f(CW\*(C`croak()\*(C'\fR and \f(CW\*(C`confess()\*(C'\fR functions. .SS "Some module prints messages to \s-1STDERR.\s0 How can I funnel them to Log::Log4perl?" .IX Subsection "Some module prints messages to STDERR. How can I funnel them to Log::Log4perl?" If a module you're using doesn't use Log::Log4perl but prints logging messages to \s-1STDERR\s0 instead, like .PP .Vb 3 \& ######################################## \& package IgnorantModule; \& ######################################## \& \& sub some_method { \& print STDERR "Parbleu! An error!\en"; \& } \& \& 1; .Ve .PP there's still a way to capture these messages and funnel them into Log::Log4perl, even without touching the module. What you need is a trapper module like .PP .Vb 3 \& ######################################## \& package Trapper; \& ######################################## \& \& use Log::Log4perl qw(:easy); \& \& sub TIEHANDLE { \& my $class = shift; \& bless [], $class; \& } \& \& sub PRINT { \& my $self = shift; \& $Log::Log4perl::caller_depth++; \& DEBUG @_; \& $Log::Log4perl::caller_depth\-\-; \& } \& \& 1; .Ve .PP and a \f(CW\*(C`tie\*(C'\fR command in the main program to tie \s-1STDERR\s0 to the trapper module along with regular Log::Log4perl initialization: .PP .Vb 3 \& ######################################## \& package main; \& ######################################## \& \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->easy_init( \& {level => $DEBUG, \& file => \*(Aqstdout\*(Aq, # make sure not to use stderr here! \& layout => "%d %M: %m%n", \& }); \& \& tie *STDERR, "Trapper"; .Ve .PP Make sure not to use \s-1STDERR\s0 as Log::Log4perl's file appender here (which would be the default in \f(CW\*(C`:easy\*(C'\fR mode), because it would end up in an endless recursion. .PP Now, calling .PP .Vb 1 \& IgnorantModule::some_method(); .Ve .PP will result in the desired output .PP .Vb 1 \& 2004/05/06 11:13:04 IgnorantModule::some_method: Parbleu! An error! .Ve .SS "How come \s-1PAR \s0(Perl Archive Toolkit) creates executables which then can't find their Log::Log4perl appenders?" .IX Subsection "How come PAR (Perl Archive Toolkit) creates executables which then can't find their Log::Log4perl appenders?" If not instructed otherwise, \f(CW\*(C`Log::Log4perl\*(C'\fR dynamically pulls in appender classes found in its configuration. If you specify .PP .Vb 2 \& #!/usr/bin/perl \& # mytest.pl \& \& use Log::Log4perl qw(get_logger); \& \& my $conf = q( \& log4perl.category.Bar.Twix = WARN, Logfile \& log4perl.appender.Logfile = Log::Log4perl::Appender::Screen \& log4perl.appender.Logfile.layout = SimpleLayout \& ); \& \& Log::Log4perl::init(\e$conf); \& my $logger = get_logger("Bar::Twix"); \& $logger\->error("Blah"); .Ve .PP then \f(CW\*(C`Log::Log4perl::Appender::Screen\*(C'\fR will be pulled in while the program runs, not at compile time. If you have \s-1PAR\s0 compile the script above to an executable binary via .PP .Vb 1 \& pp \-o mytest mytest.pl .Ve .PP and then run \f(CW\*(C`mytest\*(C'\fR on a machine without having Log::Log4perl installed, you'll get an error message like .PP .Vb 2 \& ERROR: can\*(Aqt load appenderclass \*(AqLog::Log4perl::Appender::Screen\*(Aq \& Can\*(Aqt locate Log/Log4perl/Appender/Screen.pm in @INC ... .Ve .PP Why? At compile time, \f(CW\*(C`pp\*(C'\fR didn't realize that \&\f(CW\*(C`Log::Log4perl::Appender::Screen\*(C'\fR would be needed later on and didn't wrap it into the executable created. To avoid this, either say \&\f(CW\*(C`use Log::Log4perl::Appender::Screen\*(C'\fR in the script explicitly or compile it with .PP .Vb 1 \& pp \-o mytest \-M Log::Log4perl::Appender::Screen mytest.pl .Ve .PP to make sure the appender class gets included. .SS "How can I access a custom appender defined in the configuration?" .IX Subsection "How can I access a custom appender defined in the configuration?" Any appender defined in the configuration file or somewhere in the code can be accessed later via \&\f(CW\*(C`Log::Log4perl\->appender_by_name("appender_name")\*(C'\fR, which returns a reference of the appender object. .PP Once you've got a hold of the object, it can be queried or modified to your liking. For example, see the custom \f(CW\*(C`IndentAppender\*(C'\fR defined below: After calling \f(CW\*(C`init()\*(C'\fR to define the Log4perl settings, the appender object is retrieved to call its \f(CW\*(C`indent_more()\*(C'\fR and \f(CW\*(C`indent_less()\*(C'\fR methods to control indentation of messages: .PP .Vb 1 \& package IndentAppender; \& \& sub new { \& bless { indent => 0 }, $_[0]; \& } \& \& sub indent_more { $_[0]\->{indent}++ } \& sub indent_less { $_[0]\->{indent}\-\- } \& \& sub log { \& my($self, %params) = @_; \& print " " x $self\->{indent}, $params{message}; \& } \& \& package main; \& \& use Log::Log4perl qw(:easy); \& \& my $conf = q( \& log4perl.category = DEBUG, Indented \& log4perl.appender.Indented = IndentAppender \& log4perl.appender.Indented.layout = Log::Log4perl::Layout::SimpleLayout \& ); \& \& Log::Log4perl::init(\e$conf); \& \& my $appender = Log::Log4perl\->appender_by_name("Indented"); \& \& DEBUG "No identation"; \& $appender\->indent_more(); \& DEBUG "One more"; \& $appender\->indent_more(); \& DEBUG "Two more"; \& $appender\->indent_less(); \& DEBUG "One less"; .Ve .PP As you would expect, this will print .PP .Vb 4 \& DEBUG \- No identation \& DEBUG \- One more \& DEBUG \- Two more \& DEBUG \- One less .Ve .PP because the very appender used by Log4perl is modified dynamically at runtime. .SS "I don't know if Log::Log4perl is installed. How can I prepare my script?" .IX Subsection "I don't know if Log::Log4perl is installed. How can I prepare my script?" In case your script needs to be prepared for environments that may or may not have Log::Log4perl installed, there's a trick. .PP If you put the following \s-1BEGIN\s0 blocks at the top of the program, you'll be able to use the \s-1\fIDEBUG\s0()\fR, \s-1\fIINFO\s0()\fR, etc. macros in Log::Log4perl's \f(CW\*(C`:easy\*(C'\fR mode. If Log::Log4perl is installed in the target environment, the regular Log::Log4perl rules apply. If not, all of \s-1\fIDEBUG\s0()\fR, \s-1\fIINFO\s0()\fR, etc. are \*(L"stubbed\*(R" out, i.e. they turn into no-ops: .PP .Vb 2 \& use warnings; \& use strict; \& \& BEGIN { \& eval { require Log::Log4perl; }; \& \& if($@) { \& print "Log::Log4perl not installed \- stubbing.\en"; \& no strict qw(refs); \& *{"main::$_"} = sub { } for qw(DEBUG INFO WARN ERROR FATAL); \& } else { \& no warnings; \& print "Log::Log4perl installed \- life is good.\en"; \& require Log::Log4perl::Level; \& Log::Log4perl::Level\->import(_\|_PACKAGE_\|_); \& Log::Log4perl\->import(qw(:easy)); \& Log::Log4perl\->easy_init($main::DEBUG); \& } \& } \& \& # The regular script begins ... \& DEBUG "Hey now!"; .Ve .PP This snippet will first probe for Log::Log4perl, and if it can't be found, it will alias \s-1\fIDEBUG\s0()\fR, \s-1\fIINFO\s0()\fR, with empty subroutines via typeglobs. If Log::Log4perl is available, its level constants are first imported (\f(CW$DEBUG\fR, \f(CW$INFO\fR, etc.) and then \f(CW\*(C`easy_init()\*(C'\fR gets called to initialize the logging system. .SS "Can file appenders create files with different permissions?" .IX Subsection "Can file appenders create files with different permissions?" Typically, when \f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR creates a new file, its permissions are set to \f(CW\*(C`rw\-r\-\-r\-\-\*(C'\fR. Why? Because your environment's \fIumask\fR most likely defaults to \&\f(CW0022\fR, that's the standard setting. .PP What's a \fIumask\fR, you're asking? It's a template that's applied to the permissions of all newly created files. While calls like \&\f(CW\*(C`open(FILE, ">foo")\*(C'\fR will always try to create files in \f(CW\*(C`rw\-rw\-rw\- \&\*(C'\fR mode, the system will apply the current \fIumask\fR template to determine the final permission setting. \fIumask\fR is a bit mask that's inverted and then applied to the requested permission setting, using a bitwise \s-1AND:\s0 .PP .Vb 1 \& $request_permission &~ $umask .Ve .PP So, a \fIumask\fR setting of 0000 (the leading 0 simply indicates an octal value) will create files in \f(CW\*(C`rw\-rw\-rw\-\*(C'\fR mode, a setting of 0277 will use \f(CW\*(C`r\-\-\-\-\-\-\-\-\*(C'\fR, and the standard 0022 will use \f(CW\*(C`rw\-r\-\-r\-\-\*(C'\fR. .PP As an example, if you want your log files to be created with \&\f(CW\*(C`rw\-r\-\-rw\-\*(C'\fR permissions, use a \fIumask\fR of \f(CW0020\fR before calling Log::Log4perl\->\fIinit()\fR: .PP .Vb 1 \& use Log::Log4perl; \& \& umask 0020; \& # Creates log.out in rw\-r\-\-rw mode \& Log::Log4perl\->init(\e q{ \& log4perl.logger = WARN, File \& log4perl.appender.File = Log::Log4perl::Appender::File \& log4perl.appender.File.filename = log.out \& log4perl.appender.File.layout = SimpleLayout \& }); .Ve .SS "Using Log4perl in an \s-1END\s0 block causes a problem!" .IX Subsection "Using Log4perl in an END block causes a problem!" It's not easy to get to this error, but if you write something like .PP .Vb 1 \& END { Log::Log4perl::get_logger()\->debug("Hey there."); } \& \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); .Ve .PP it won't work. The reason is that \f(CW\*(C`Log::Log4perl\*(C'\fR defines an \&\s-1END\s0 block that cleans up all loggers. And perl will run \s-1END\s0 blocks in the reverse order as they're encountered in the compile phase, so in the scenario above, the \s-1END\s0 block will run \fIafter\fR Log4perl has cleaned up its loggers. .PP Placing \s-1END\s0 blocks using Log4perl \fIafter\fR a \f(CW\*(C`use Log::Log4perl\*(C'\fR statement fixes the problem: .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); \& \& END { Log::Log4perl::get_logger()\->debug("Hey there."); } .Ve .PP In this scenario, the shown \s-1END\s0 block is executed \fIbefore\fR Log4perl cleans up and the debug message will be processed properly. .ie n .SS "Help! My appender is throwing a ""Wide character in print"" warning!" .el .SS "Help! My appender is throwing a ``Wide character in print'' warning!" .IX Subsection "Help! My appender is throwing a Wide character in print warning!" This warning shows up when Unicode strings are printed without precautions. The warning goes away if the complaining appender is set to utf\-8 mode: .PP .Vb 3 \& # Either in the log4perl configuration file: \& log4perl.appender.Logfile.filename = test.log \& log4perl.appender.Logfile.utf8 = 1 \& \& # Or, in easy mode: \& Log::Log4perl\->easy_init( { \& level => $DEBUG, \& file => ":utf8> test.log" \& } ); .Ve .PP If the complaining appender is a screen appender, set its \f(CW\*(C`utf8\*(C'\fR option: .PP .Vb 2 \& log4perl.appender.Screen.stderr = 1 \& log4perl.appender.Screen.utf8 = 1 .Ve .PP Alternatively, \f(CW\*(C`binmode\*(C'\fR does the trick: .PP .Vb 2 \& # Either STDOUT ... \& binmode(STDOUT, ":utf8); \& \& # ... or STDERR. \& binmode(STDERR, ":utf8); .Ve .PP Some background on this: Perl's strings are either byte strings or Unicode strings. \f(CW"Mike"\fR is a byte string. \&\f(CW"\ex{30DE}\ex{30A4}\ex{30AF}"\fR is a Unicode string. Unicode strings are marked specially and are \s-1UTF\-8\s0 encoded internally. .PP If you print a byte string to \s-1STDOUT,\s0 all is well, because \s-1STDOUT\s0 is by default set to byte mode. However, if you print a Unicode string to \s-1STDOUT\s0 without precautions, \f(CW\*(C`perl\*(C'\fR will try to transform the Unicode string back to a byte string before printing it out. This is troublesome if the Unicode string contains \&'wide' characters which can't be represented in Latin\-1. .PP For example, if you create a Unicode string with three japanese Katakana characters as in .PP .Vb 1 \& perl \-le \*(Aqprint "\ex{30DE}\ex{30A4}\ex{30AF}"\*(Aq .Ve .PP (coincidentally pronounced Ma-i-ku, the japanese pronunciation of \&\*(L"Mike\*(R"), \s-1STDOUT\s0 is in byte mode and the warning .PP .Vb 1 \& Wide character in print at ./script.pl line 14. .Ve .PP appears. Setting \s-1STDOUT\s0 to \s-1UTF\-8\s0 mode as in .PP .Vb 1 \& perl \-le \*(Aqbinmode(STDOUT, ":utf8"); print "\ex{30DE}\ex{30A4}\ex{30AF}"\*(Aq .Ve .PP will silently print the Unicode string to \s-1STDOUT\s0 in \s-1UTF\-8.\s0 To see the characters printed, you'll need a \s-1UTF\-8\s0 terminal with a font including japanese Katakana characters. .SS "How can I send errors to the screen, and debug messages to a file?" .IX Subsection "How can I send errors to the screen, and debug messages to a file?" Let's assume you want to maintain a detailed \s-1DEBUG\s0 output in a file and only messages of level \s-1ERROR\s0 and higher should be printed on the screen. Often times, developers come up with something like this: .PP .Vb 4 \& # Wrong!!! \& log4perl.logger = DEBUG, FileApp \& log4perl.logger = ERROR, ScreenApp \& # Wrong!!! .Ve .PP This won't work, however. Logger definitions aren't additive, and the second statement will overwrite the first one. Log4perl versions below 1.04 were silently accepting this, leaving people confused why it wouldn't work as expected. As of 1.04, this will throw a \fIfatal error\fR to notify the user of the problem. .PP What you want to do instead, is this: .PP .Vb 1 \& log4perl.logger = DEBUG, FileApp, ScreenApp \& \& log4perl.appender.FileApp = Log::Log4perl::Appender::File \& log4perl.appender.FileApp.filename = test.log \& log4perl.appender.FileApp.layout = SimpleLayout \& \& log4perl.appender.ScreenApp = Log::Log4perl::Appender::Screen \& log4perl.appender.ScreenApp.stderr = 0 \& log4perl.appender.ScreenApp.layout = SimpleLayout \& ### limiting output to ERROR messages \& log4perl.appender.ScreenApp.Threshold = ERROR \& ### .Ve .PP Note that without the second appender's \f(CW\*(C`Threshold\*(C'\fR setting, both appenders would receive all messages prioritized \s-1DEBUG\s0 and higher. With the threshold set to \s-1ERROR,\s0 the second appender will filter the messages as required. .SS "Where should I put my logfiles?" .IX Subsection "Where should I put my logfiles?" Your log files may go anywhere you want them, but the effective user id of the calling process must have write access. .PP If the log file doesn't exist at program start, Log4perl's file appender will create it. For this, it needs write access to the directory where the new file will be located in. If the log file already exists at startup, the process simply needs write access to the file. Note that it will need write access to the file's directory if you're encountering situations where the logfile gets recreated, e.g. during log rotation. .PP If Log::Log4perl is used by a web server application (e.g. in a \s-1CGI\s0 script or mod_perl), then the webserver's user (usually \f(CW\*(C`nobody\*(C'\fR or \f(CW\*(C`www\*(C'\fR) must have the permissions mentioned above. .PP To prepare your web server to use log4perl, we'd recommend: .PP .Vb 5 \& webserver:~$ su \- \& webserver:~# mkdir /var/log/cgiapps \& webserver:~# chown nobody:root /var/log/cgiapps/ \& webserver:~# chown nobody:root \-R /var/log/cgiapps/ \& webserver:~# chmod 02755 \-R /var/log/cgiapps/ .Ve .PP Then set your /etc/log4perl.conf file to include: .PP .Vb 2 \& log4perl.appender.FileAppndr1.filename = \& /var/log/cgiapps/<app\-name>.log .Ve .SS "How can my file appender deal with disappearing log files?" .IX Subsection "How can my file appender deal with disappearing log files?" The file appender that comes with Log4perl, Log::Log4perl::Appender::File, will open a specified log file at initialization time and will keep writing to it via a file handle. .PP In case the associated file goes way, messages written by a long-running process will still be written to the file handle. In case the file has been moved to a different location on the same file system, the writer will keep writing to it under the new filename. In case the file has been removed from the file system, the log messages will end up in nowhere land. This is not a bug in Log4perl, this is how Unix works. There is no error message in this case, because the writer has no idea that the file handle is not associated with a visible file. .PP To prevent the loss of log messages when log files disappear, the file appender's \f(CW\*(C`recreate\*(C'\fR option needs to be set to a true value: .PP .Vb 1 \& log4perl.appender.Logfile.recreate = 1 .Ve .PP This will instruct the file appender to check in regular intervals (default: 30 seconds) if the log file is still there. If it finds out that the file is missing, it will recreate it. .PP Continuously checking if the log file still exists is fairly expensive. For this reason it is only performed every 30 seconds. To change this interval, the option \f(CW\*(C`recreate_check_interval\*(C'\fR can be set to the number of seconds between checks. In the extreme case where the check should be performed before every write, it can even be set to 0: .PP .Vb 2 \& log4perl.appender.Logfile.recreate = 1 \& log4perl.appender.Logfile.recreate_check_interval = 0 .Ve .PP To avoid having to check the file system so frequently, a signal handler can be set up: .PP .Vb 2 \& log4perl.appender.Logfile.recreate = 1 \& log4perl.appender.Logfile.recreate_check_signal = USR1 .Ve .PP This will install a signal handler which will recreate a missing log file immediately when it receives the defined signal. .PP Note that the \fIinit_and_watch()\fR method for Log4perl's initialization can also be instructed to install a signal handler, usually using the \&\s-1HUP\s0 signal. Make sure to use a different signal if you're using both of them at the same time. .SS "How can I rotate a logfile with newsyslog?" .IX Subsection "How can I rotate a logfile with newsyslog?" Here's a few things that need to be taken care of when using the popular log file rotating utility \f(CW\*(C`newsyslog\*(C'\fR (http://www.courtesan.com/newsyslog) with Log4perl's file appender in long-running processes. .PP For example, with a newsyslog configuration like .PP .Vb 2 \& # newsyslog.conf \& /tmp/test.log 666 12 5 * B .Ve .PP and a call to .PP .Vb 1 \& # newsyslog \-f /path/to/newsyslog.conf .Ve .PP \&\f(CW\*(C`newsyslog\*(C'\fR will take action if \f(CW\*(C`/tmp/test.log\*(C'\fR is larger than the specified 5K in size. It will move the current log file \f(CW\*(C`/tmp/test.log\*(C'\fR to \&\f(CW\*(C`/tmp/test.log.0\*(C'\fR and create a new and empty \f(CW\*(C`/tmp/test.log\*(C'\fR with the specified permissions (this is why \f(CW\*(C`newsyslog\*(C'\fR needs to run as root). An already existing \f(CW\*(C`/tmp/test.log.0\*(C'\fR would be moved to \&\f(CW\*(C`/tmp/test.log.1\*(C'\fR, \f(CW\*(C`/tmp/test.log.1\*(C'\fR to \f(CW\*(C`/tmp/test.log.2\*(C'\fR, and so forth, for every one of a max number of 12 archived logfiles that have been configured in \f(CW\*(C`newsyslog.conf\*(C'\fR. .PP Although a new file has been created, from Log4perl's appender's point of view, this situation is identical to the one described in the previous \s-1FAQ\s0 entry, labeled \f(CW\*(C`How can my file appender deal with disappearing log files\*(C'\fR. .PP To make sure that log messages are written to the new log file and not to an archived one or end up in nowhere land, the appender's \f(CW\*(C`recreate\*(C'\fR and \f(CW\*(C`recreate_check_interval\*(C'\fR have to be configured to deal with the 'disappearing' log file. .PP The situation gets interesting when \f(CW\*(C`newsyslog\*(C'\fR's option to compress archived log files is enabled. This causes the original log file not to be moved, but to disappear. If the file appender isn't configured to recreate the logfile in this situation, log messages will actually be lost without warning. This also applies for the short time frame of \f(CW\*(C`recreate_check_interval\*(C'\fR seconds in between the recreator's file checks. .PP To make sure that no messages get lost, one option is to set the interval to .PP .Vb 1 \& log4perl.appender.Logfile.recreate_check_interval = 0 .Ve .PP However, this is fairly expensive. A better approach is to define a signal handler: .PP .Vb 3 \& log4perl.appender.Logfile.recreate = 1 \& log4perl.appender.Logfile.recreate_check_signal = USR1 \& log4perl.appender.Logfile.recreate_pid_write = /tmp/myappid .Ve .PP As a service for \f(CW\*(C`newsyslog\*(C'\fR users, Log4perl's file appender writes the current process \s-1ID\s0 to a \s-1PID\s0 file specified by the \f(CW\*(C`recreate_pid_write\*(C'\fR option. \f(CW\*(C`newsyslog\*(C'\fR then needs to be configured as in .PP .Vb 3 \& # newsyslog.conf configuration for compressing archive files and \& # sending a signal to the Log4perl\-enabled application \& /tmp/test.log 666 12 5 * B /tmp/myappid 30 .Ve .PP to send the defined signal (30, which is \s-1USR1\s0 on FreeBSD) to the application process at rotation time. Note that the signal number is different on Linux, where \s-1USR1\s0 denotes as 10. Check \f(CW\*(C`man signal\*(C'\fR for details. .SS "How can a process under user id A log to a file under user id B?" .IX Subsection "How can a process under user id A log to a file under user id B?" This scenario often occurs in configurations where processes run under various user IDs but need to write to a log file under a fixed, but different user id. .PP With a traditional file appender, the log file will probably be created under one user's id and appended to under a different user's id. With a typical umask of 0002, the file will be created with \-rw\-rw\-r\*(-- permissions. If a user who's not in the first user's group subsequently appends to the log file, it will fail because of a permission problem. .PP Two potential solutions come to mind: .IP "\(bu" 4 Creating the file with a umask of 0000 will allow all users to append to the log file. Log4perl's file appender \f(CW\*(C`Log::Log4perl::Appender::File\*(C'\fR has an \f(CW\*(C`umask\*(C'\fR option that can be set to support this: .Sp .Vb 2 \& log4perl.appender.File = Log::Log4perl::Appender::File \& log4perl.appender.File.umask = sub { 0000 }; .Ve .Sp This way, the log file will be created with \-rw\-rw\-rw\- permissions and therefore has world write permissions. This might open up the logfile for unwanted manipulations by arbitrary users, though. .IP "\(bu" 4 Running the process under an effective user id of \f(CW\*(C`root\*(C'\fR will allow it to write to the log file, no matter who started the process. However, this is not a good idea, because of security concerns. .PP Luckily, under Unix, there's the syslog daemon which runs as root and takes log requests from user processes over a socket and writes them to log files as configured in \f(CW\*(C`/etc/syslog.conf\*(C'\fR. .PP By modifying \f(CW\*(C`/etc/syslog.conf\*(C'\fR and HUPing the syslog daemon, you can configure new log files: .PP .Vb 3 \& # /etc/syslog.conf \& ... \& user.* /some/path/file.log .Ve .PP Using the \f(CW\*(C`Log::Dispatch::Syslog\*(C'\fR appender, which comes with the \&\f(CW\*(C`Log::Log4perl\*(C'\fR distribution, you can then send messages via syslog: .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->init(\e<<EOT); \& log4perl.logger = DEBUG, app \& log4perl.appender.app=Log::Dispatch::Syslog \& log4perl.appender.app.Facility=user \& log4perl.appender.app.layout=SimpleLayout \& EOT \& \& # Writes to /some/path/file.log \& ERROR "Message!"; .Ve .PP This way, the syslog daemon will solve the permission problem. .PP Note that while it is possible to use \fIsyslog()\fR without Log4perl (syslog supports log levels, too), traditional syslog setups have a significant drawback. .PP Without Log4perl's ability to activate logging in only specific parts of a system, complex systems will trigger log events all over the place and slow down execution to a crawl at high debug levels. .PP Remote-controlling logging in the hierarchical parts of an application via Log4perl's categories is one of its most distinguished features. It allows for enabling high debug levels in specified areas without noticeable performance impact. .SS "I want to use \s-1UTC\s0 instead of the local time!" .IX Subsection "I want to use UTC instead of the local time!" If a layout defines a date, Log::Log4perl uses local time to populate it. If you want \s-1UTC\s0 instead, set .PP .Vb 1 \& log4perl.utcDateTimes = 1 .Ve .PP in your configuration. Alternatively, you can set .PP .Vb 1 \& $Log::Log4perl::DateFormat::GMTIME = 1; .Ve .PP in your program before the first log statement. .SS "Can Log4perl intercept messages written to a filehandle?" .IX Subsection "Can Log4perl intercept messages written to a filehandle?" You have a function that prints to a filehandle. You want to tie into that filehandle and forward all arriving messages to a Log4perl logger. .PP First, let's write a package that ties a file handle and forwards it to a Log4perl logger: .PP .Vb 2 \& package FileHandleLogger; \& use Log::Log4perl qw(:levels get_logger); \& \& sub TIEHANDLE { \& my($class, %options) = @_; \& \& my $self = { \& level => $DEBUG, \& category => \*(Aq\*(Aq, \& %options \& }; \& \& $self\->{logger} = get_logger($self\->{category}), \& bless $self, $class; \& } \& \& sub PRINT { \& my($self, @rest) = @_; \& $Log::Log4perl::caller_depth++; \& $self\->{logger}\->log($self\->{level}, @rest); \& $Log::Log4perl::caller_depth\-\-; \& } \& \& sub PRINTF { \& my($self, $fmt, @rest) = @_; \& $Log::Log4perl::caller_depth++; \& $self\->PRINT(sprintf($fmt, @rest)); \& $Log::Log4perl::caller_depth\-\-; \& } \& \& 1; .Ve .PP Now, if you have a function like .PP .Vb 4 \& sub function_printing_to_fh { \& my($fh) = @_; \& printf $fh "Hi there!\en"; \& } .Ve .PP which takes a filehandle and prints something to it, it can be used with Log4perl: .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& usa FileHandleLogger; \& \& Log::Log4perl\->easy_init($DEBUG); \& \& tie *SOMEHANDLE, \*(AqFileHandleLogger\*(Aq or \& die "tie failed ($!)"; \& \& function_printing_to_fh(*SOMEHANDLE); \& # prints "2007/03/22 21:43:30 Hi there!" .Ve .PP If you want, you can even specify a different log level or category: .PP .Vb 2 \& tie *SOMEHANDLE, \*(AqFileHandleLogger\*(Aq, \& level => $INFO, category => "Foo::Bar" or die "tie failed ($!)"; .Ve .SS "I want multiline messages rendered line-by-line!" .IX Subsection "I want multiline messages rendered line-by-line!" With the standard \f(CW\*(C`PatternLayout\*(C'\fR, if you send a multiline message to an appender as in .PP .Vb 2 \& use Log::Log4perl qw(:easy); \& Log .Ve .PP it gets rendered this way: .PP .Vb 3 \& 2007/04/04 23:23:39 multi \& line \& message .Ve .PP If you want each line to be rendered separately according to the layout use \f(CW\*(C`Log::Log4perl::Layout::PatternLayout::Multiline\*(C'\fR: .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->init(\e<<EOT); \& log4perl.category = DEBUG, Screen \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = \e\e \& Log::Log4perl::Layout::PatternLayout::Multiline \& log4perl.appender.Screen.layout.ConversionPattern = %d %m %n \& EOT \& \& DEBUG "some\enmultiline\enmessage"; .Ve .PP and you'll get .PP .Vb 3 \& 2007/04/04 23:23:39 some \& 2007/04/04 23:23:39 multiline \& 2007/04/04 23:23:39 message .Ve .PP instead. .SS "I'm on Windows and I'm getting all these 'redefined' messages!" .IX Subsection "I'm on Windows and I'm getting all these 'redefined' messages!" If you're on Windows and are getting warning messages like .PP .Vb 6 \& Constant subroutine Log::Log4perl::_INTERNAL_DEBUG redefined at \& C:/Programme/Perl/lib/constant.pm line 103. \& Subroutine import redefined at \& C:/Programme/Perl/site/lib/Log/Log4Perl.pm line 69. \& Subroutine initialized redefined at \& C:/Programme/Perl/site/lib/Log/Log4Perl.pm line 207. .Ve .PP then chances are that you're using 'Log::Log4Perl' (wrong uppercase P) instead of the correct 'Log::Log4perl'. Perl on Windows doesn't handle this error well and spits out a slew of confusing warning messages. But now you know, just use the correct module name and you'll be fine. .SS "Log4perl complains that no initialization happened during shutdown!" .IX Subsection "Log4perl complains that no initialization happened during shutdown!" If you're using Log4perl log commands in \s-1DESTROY\s0 methods of your objects, you might see confusing messages like .PP .Vb 6 \& Log4perl: Seems like no initialization happened. Forgot to call init()? \& Use of uninitialized value in subroutine entry at \& /home/y/lib/perl5/site_perl/5.6.1/Log/Log4perl.pm line 134 during global \& destruction. (in cleanup) Undefined subroutine &main:: called at \& /home/y/lib/perl5/site_perl/5.6.1/Log/Log4perl.pm line 134 during global \& destruction. .Ve .PP when the program shuts down. What's going on? .PP This phenomenon happens if you have circular references in your objects, which perl can't clean up when an object goes out of scope but waits until global destruction instead. At this time, however, Log4perl has already shut down, so you can't use it anymore. .PP For example, here's a simple class which uses a logger in its \s-1DESTROY\s0 method: .PP .Vb 4 \& package A; \& use Log::Log4perl qw(:easy); \& sub new { bless {}, shift } \& sub DESTROY { DEBUG "Waaah!"; } .Ve .PP Now, if the main program creates a self-referencing object, like in .PP .Vb 3 \& package main; \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); \& \& my $a = A\->new(); \& $a\->{selfref} = $a; .Ve .PP then you'll see the error message shown above during global destruction. How to tackle this problem? .PP First, you should clean up your circular references before global destruction. They will not only cause objects to be destroyed in an order that's hard to predict, but also eat up memory until the program shuts down. .PP So, the program above could easily be fixed by putting .PP .Vb 1 \& $a\->{selfref} = undef; .Ve .PP at the end or in an \s-1END\s0 handler. If that's hard to do, use weak references: .PP .Vb 4 \& package main; \& use Scalar::Util qw(weaken); \& use Log::Log4perl qw(:easy); \& Log::Log4perl\->easy_init($DEBUG); \& \& my $a = A\->new(); \& $a\->{selfref} = weaken $a; .Ve .PP This allows perl to clean up the circular reference when the object goes out of scope, and doesn't wait until global destruction. .SS "How can I access \s-1POE\s0 heap values from Log4perl's layout?" .IX Subsection "How can I access POE heap values from Log4perl's layout?" \&\s-1POE\s0 is a framework for creating multitasked applications running in a single process and a single thread. \s-1POE\s0's threads equivalents are \&'sessions' and since they run quasi-simultaneously, you can't use Log4perl's global \s-1NDC/MDC\s0 to hold session-specific data. .PP However, \s-1POE\s0 already maintains a data store for every session. It is called \&'heap' and is just a hash storing session-specific data in key-value pairs. To access this per-session heap data from a Log4perl layout, define a custom cspec and reference it with the newly defined pattern in the layout: .PP .Vb 3 \& use strict; \& use POE; \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->init( \e q{ \& log4perl.logger = DEBUG, Screen \& log4perl.appender.Screen = Log::Log4perl::Appender::Screen \& log4perl.appender.Screen.layout = PatternLayout \& log4perl.appender.Screen.layout.ConversionPattern = %U %m%n \& log4perl.PatternLayout.cspec.U = \e \& sub { POE::Kernel\->get_active_session\->get_heap()\->{ user } } \& } ); \& \& for (qw( Huey Lewey Dewey )) { \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[HEAP]\->{user} = $_; \& POE::Kernel\->yield(\*(Aqhello\*(Aq); \& }, \& hello => sub { \& DEBUG "I\*(Aqm here now"; \& } \& } \& ); \& } \& \& POE::Kernel\->run(); \& exit; .Ve .PP The code snippet above defines a new layout placeholder (called \&'cspec' in Log4perl) \f(CW%U\fR which calls a subroutine, retrieves the active session, gets its heap and looks up the entry specified ('user'). .PP Starting with Log::Log4perl 1.20, cspecs also support parameters in curly braces, so you can say .PP .Vb 4 \& log4perl.appender.Screen.layout.ConversionPattern = %U{user} %U{id} %m%n \& log4perl.PatternLayout.cspec.U = \e \& sub { POE::Kernel\->get_active_session\-> \e \& get_heap()\->{ $_[0]\->{curlies} } } .Ve .PP and print the \s-1POE\s0 session heap entries 'user' and 'id' with every logged message. For more details on cpecs, read the PatternLayout manual. .SS "I want to print something unconditionally!" .IX Subsection "I want to print something unconditionally!" Sometimes it's a script that's supposed to log messages regardless if Log4perl has been initialized or not. Or there's a logging statement that's not going to be suppressed under any circumstances \*(-- many people want to have the final word, make the executive decision, because it seems like the only logical choice. .PP But think about it: First off, if a messages is supposed to be printed, where is it supposed to end up at? \s-1STDOUT\s0? \s-1STDERR\s0? And are you sure you want to set in stone that this message needs to be printed, while someone else might find it annoying and wants to get rid of it? .PP The truth is, there's always going to be someone who wants to log a messages at all cost, but also another person who wants to suppress it with equal vigilance. There's no good way to serve these two conflicting desires, someone will always want to win at the cost of leaving the other party disappointed. .PP So, the best Log4perl offers is the \s-1ALWAYS\s0 level for a message that even fires if the system log level is set to \f(CW$OFF:\fR .PP .Vb 1 \& use Log::Log4perl qw(:easy); \& \& Log::Log4perl\->easy_init( $OFF ); \& ALWAYS "This gets logged always. Well, almost always"; .Ve .PP The logger won't fire, though, if Log4perl hasn't been initialized or if someone defines a custom log hurdle that's higher than \f(CW$OFF\fR. .PP Bottom line: Leave the setting of the logging level to the initial Perl script \*(-- let their owners decided what they want, no matter how tempting it may be to decide it for them. .SS "Why doesn't my \s-1END\s0 handler remove my log file on Win32?" .IX Subsection "Why doesn't my END handler remove my log file on Win32?" If you have code like .PP .Vb 3 \& use Log::Log4perl qw( :easy ); \& Log::Log4perl\->easy_init( { level => $DEBUG, file => "my.log" } ); \& END { unlink "my.log" or die }; .Ve .PP then you might be in for a surprise when you're running it on Windows, because the \f(CW\*(C`unlink()\*(C'\fR call in the \s-1END\s0 handler will complain that the file is still in use. .PP What happens in Perl if you have something like .PP .Vb 3 \& END { print "first end in main\en"; } \& use Module; \& END { print "second end in main\en"; } .Ve .PP and .PP .Vb 3 \& package Module; \& END { print "end in module\en"; } \& 1; .Ve .PP is that you get .PP .Vb 3 \& second end in main \& end in module \& first end in main .Ve .PP because perl stacks the \s-1END\s0 handlers in reverse order in which it encounters them in the compile phase. .PP Log4perl defines an \s-1END\s0 handler that cleans up left-over appenders (e.g. file appenders which still hold files open), because those appenders have circular references and therefore aren't cleaned up otherwise. .PP Now if you define an \s-1END\s0 handler after \*(L"use Log::Log4perl\*(R", it'll trigger before Log4perl gets a chance to clean up, which isn't a problem on Unix where you can delete a file even if some process has a handle to it open, but it's a problem on Win32, where the \s-1OS\s0 won't let you do that. .PP The solution is easy, just place the \s-1END\s0 handler \fIbefore\fR Log4perl gets loaded, like in .PP .Vb 3 \& END { unlink "my.log" or die }; \& use Log::Log4perl qw( :easy ); \& Log::Log4perl\->easy_init( { level => $DEBUG, file => "my.log" } ); .Ve .PP which will call the \s-1END\s0 handlers in the intended order. .SH "SEE ALSO" .IX Header "SEE ALSO" Log::Log4perl .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. .SH "AUTHOR" .IX Header "AUTHOR" 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.