PageRenderTime 67ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Log/Log4perl/FAQ.pm

http://github.com/mschilli/log4perl
Perl | 2682 lines | 2312 code | 342 blank | 28 comment | 62 complexity | 51b64d8cfcff20a09b0585042519150a MD5 | raw file
  1. 1;
  2. __END__
  3. =encoding utf8
  4. =head1 NAME
  5. Log::Log4perl::FAQ - Frequently Asked Questions on Log::Log4perl
  6. =head1 DESCRIPTION
  7. This FAQ shows a wide variety of
  8. commonly encountered logging tasks and how to solve them
  9. in the most elegant way with Log::Log4perl. Most of the time, this will
  10. be just a matter of smartly configuring your Log::Log4perl configuration files.
  11. =head2 Why use Log::Log4perl instead of any other logging module on CPAN?
  12. That's a good question. There's dozens of logging modules on CPAN.
  13. When it comes to logging, people typically think: "Aha. Writing out
  14. debug and error messages. Debug is lower than error. Easy. I'm gonna
  15. write my own." Writing a logging module is like a rite of passage for
  16. every Perl programmer, just like writing your own templating system.
  17. Of course, after getting the basics right, features need to
  18. be added. You'd like to write a timestamp with every message. Then
  19. timestamps with microseconds. Then messages need to be written to both
  20. the screen and a log file.
  21. And, as your application grows in size you might wonder: Why doesn't
  22. my logging system scale along with it? You would like to switch on
  23. logging in selected parts of the application, and not all across the
  24. board, because this kills performance. This is when people turn to
  25. Log::Log4perl, because it handles all of that.
  26. Avoid this costly switch.
  27. Use C<Log::Log4perl> right from the start. C<Log::Log4perl>'s C<:easy>
  28. mode supports easy logging in simple scripts:
  29. use Log::Log4perl qw(:easy);
  30. Log::Log4perl->easy_init($DEBUG);
  31. DEBUG "A low-level message";
  32. ERROR "Won't make it until level gets increased to ERROR";
  33. And when your application inevitably grows, your logging system grows
  34. with it without you having to change any code.
  35. Please, don't re-invent logging. C<Log::Log4perl> is here, it's easy
  36. to use, it scales, and covers many areas you haven't thought of yet,
  37. but will enter soon.
  38. =head2 What's the easiest way to use Log4perl?
  39. If you just want to get all the comfort of logging, without much
  40. overhead, use I<Stealth Loggers>. If you use Log::Log4perl in
  41. C<:easy> mode like
  42. use Log::Log4perl qw(:easy);
  43. you'll have the following functions available in the current package:
  44. DEBUG("message");
  45. INFO("message");
  46. WARN("message");
  47. ERROR("message");
  48. FATAL("message");
  49. Just make sure that every package of your code where you're using them in
  50. pulls in C<use Log::Log4perl qw(:easy)> first, then you're set.
  51. Every stealth logger's category will be equivalent to the name of the
  52. package it's located in.
  53. These stealth loggers
  54. will be absolutely silent until you initialize Log::Log4perl in
  55. your main program with either
  56. # Define any Log4perl behavior
  57. Log::Log4perl->init("foo.conf");
  58. (using a full-blown Log4perl config file) or the super-easy method
  59. # Just log to STDERR
  60. Log::Log4perl->easy_init($DEBUG);
  61. or the parameter-style method with a complexity somewhat in between:
  62. # Append to a log file
  63. Log::Log4perl->easy_init( { level => $DEBUG,
  64. file => ">>test.log" } );
  65. For more info, please check out L<Log::Log4perl/"Stealth Loggers">.
  66. =head2 How can I simply log all my ERROR messages to a file?
  67. After pulling in the C<Log::Log4perl> module, just initialize its
  68. behavior by passing in a configuration to its C<init> method as a string
  69. reference. Then, obtain a logger instance and write out a message
  70. with its C<error()> method:
  71. use Log::Log4perl qw(get_logger);
  72. # Define configuration
  73. my $conf = q(
  74. log4perl.logger = ERROR, FileApp
  75. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  76. log4perl.appender.FileApp.filename = test.log
  77. log4perl.appender.FileApp.layout = PatternLayout
  78. log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n
  79. );
  80. # Initialize logging behavior
  81. Log::Log4perl->init( \$conf );
  82. # Obtain a logger instance
  83. my $logger = get_logger("Bar::Twix");
  84. $logger->error("Oh my, a dreadful error!");
  85. $logger->warn("Oh my, a dreadful warning!");
  86. This will append something like
  87. 2002/10/29 20:11:55> Oh my, a dreadful error!
  88. to the log file C<test.log>. How does this all work?
  89. While the Log::Log4perl C<init()> method typically
  90. takes the name of a configuration file as its input parameter like
  91. in
  92. Log::Log4perl->init( "/path/mylog.conf" );
  93. the example above shows how to pass in a configuration as text in a
  94. scalar reference.
  95. The configuration as shown
  96. defines a logger of the root category, which has an appender of type
  97. C<Log::Log4perl::Appender::File> attached. The line
  98. log4perl.logger = ERROR, FileApp
  99. doesn't list a category, defining a root logger. Compare that with
  100. log4perl.logger.Bar.Twix = ERROR, FileApp
  101. which would define a logger for the category C<Bar::Twix>,
  102. showing probably different behavior. C<FileApp> on
  103. the right side of the assignment is
  104. an arbitrarily defined variable name, which is only used to somehow
  105. reference an appender defined later on.
  106. Appender settings in the configuration are defined as follows:
  107. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  108. log4perl.appender.FileApp.filename = test.log
  109. It selects the file appender of the C<Log::Log4perl::Appender>
  110. hierarchy, which will append to the file C<test.log> if it already
  111. exists. If we wanted to overwrite a potentially existing file, we would
  112. have to explicitly set the appropriate C<Log::Log4perl::Appender::File>
  113. parameter C<mode>:
  114. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  115. log4perl.appender.FileApp.filename = test.log
  116. log4perl.appender.FileApp.mode = write
  117. Also, the configuration defines a PatternLayout format, adding
  118. the nicely formatted current date and time, an arrow (E<gt>) and
  119. a space before the messages, which is then followed by a newline:
  120. log4perl.appender.FileApp.layout = PatternLayout
  121. log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n
  122. Obtaining a logger instance and actually logging something is typically
  123. done in a different system part as the Log::Log4perl initialisation section,
  124. but in this example, it's just done right after init for the
  125. sake of compactness:
  126. # Obtain a logger instance
  127. my $logger = get_logger("Bar::Twix");
  128. $logger->error("Oh my, a dreadful error!");
  129. This retrieves an instance of the logger of the category C<Bar::Twix>,
  130. which, as all other categories, inherits behavior from the root logger if no
  131. other loggers are defined in the initialization section.
  132. The C<error()>
  133. method fires up a message, which the root logger catches. Its
  134. priority is equal to
  135. or higher than the root logger's priority (ERROR), which causes the root logger
  136. to forward it to its attached appender. By contrast, the following
  137. $logger->warn("Oh my, a dreadful warning!");
  138. doesn't make it through, because the root logger sports a higher setting
  139. (ERROR and up) than the WARN priority of the message.
  140. =head2 How can I install Log::Log4perl on Microsoft Windows?
  141. You can install Log::Log4perl using the CPAN client.
  142. Alternatively you can install it using
  143. ppm install Log-Log4perl
  144. if you're using ActiveState perl.
  145. That's it! Afterwards, just create a Perl script like
  146. use Log::Log4perl qw(:easy);
  147. Log::Log4perl->easy_init($DEBUG);
  148. my $logger = get_logger("Twix::Bar");
  149. $logger->debug("Watch me!");
  150. and run it. It should print something like
  151. 2002/11/06 01:22:05 Watch me!
  152. If you find that something doesn't work, please let us know at
  153. log4perl-devel@lists.sourceforge.net -- we'll appreciate it. Have fun!
  154. =head2 How can I include global (thread-specific) data in my log messages?
  155. Say, you're writing a web application and want all your
  156. log messages to include the current client's IP address. Most certainly,
  157. you don't want to include it in each and every log message like in
  158. $logger->debug( $r->connection->remote_ip,
  159. " Retrieving user data from DB" );
  160. do you? Instead, you want to set it in a global data structure and
  161. have Log::Log4perl include it automatically via a PatternLayout setting
  162. in the configuration file:
  163. log4perl.appender.FileApp.layout.ConversionPattern = %X{ip} %m%n
  164. The conversion specifier C<%X{ip}> references an entry under the key
  165. C<ip> in the global C<MDC> (mapped diagnostic context) table, which
  166. you've set once via
  167. Log::Log4perl::MDC->put("ip", $r->connection->remote_ip);
  168. at the start of the request handler. Note that this is a
  169. I<static> (class) method, there's no logger object involved.
  170. You can use this method with as many key/value pairs as you like as long
  171. as you reference them under different names.
  172. The mappings are stored in a global hash table within Log::Log4perl.
  173. Luckily, because the thread
  174. model in 5.8.0 doesn't share global variables between threads unless
  175. they're explicitly marked as such, there's no problem with multi-threaded
  176. environments.
  177. For more details on the MDC, please refer to
  178. L<Log::Log4perl/"Mapped Diagnostic Context (MDC)"> and
  179. L<Log::Log4perl::MDC>.
  180. =head2 My application is already logging to a file. How can I duplicate all messages to also go to the screen?
  181. Assuming that you already have a Log4perl configuration file like
  182. log4perl.logger = DEBUG, FileApp
  183. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  184. log4perl.appender.FileApp.filename = test.log
  185. log4perl.appender.FileApp.layout = PatternLayout
  186. log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n
  187. and log statements all over your code,
  188. it's very easy with Log4perl to have the same messages both printed to
  189. the logfile and the screen. No reason to change your code, of course,
  190. just add another appender to the configuration file and you're done:
  191. log4perl.logger = DEBUG, FileApp, ScreenApp
  192. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  193. log4perl.appender.FileApp.filename = test.log
  194. log4perl.appender.FileApp.layout = PatternLayout
  195. log4perl.appender.FileApp.layout.ConversionPattern = %d> %m%n
  196. log4perl.appender.ScreenApp = Log::Log4perl::Appender::Screen
  197. log4perl.appender.ScreenApp.stderr = 0
  198. log4perl.appender.ScreenApp.layout = PatternLayout
  199. log4perl.appender.ScreenApp.layout.ConversionPattern = %d> %m%n
  200. The configuration file above is assuming that both appenders are
  201. active in the same logger hierarchy, in this case the C<root> category.
  202. But even if you've got file loggers defined in several parts of your system,
  203. belonging to different logger categories,
  204. each logging to different files, you can gobble up all logged messages
  205. by defining a root logger with a screen appender, which would duplicate
  206. messages from all your file loggers to the screen due to Log4perl's
  207. appender inheritance. Check
  208. http://www.perl.com/pub/a/2002/09/11/log4perl.html
  209. for details. Have fun!
  210. =head2 How can I make sure my application logs a message when it dies unexpectedly?
  211. Whenever you encounter a fatal error in your application, instead of saying
  212. something like
  213. open FILE, "<blah" or die "Can't open blah -- bailing out!";
  214. just use Log::Log4perl's fatal functions instead:
  215. my $log = get_logger("Some::Package");
  216. open FILE, "<blah" or $log->logdie("Can't open blah -- bailing out!");
  217. This will both log the message with priority FATAL according to your current
  218. Log::Log4perl configuration and then call Perl's C<die()>
  219. afterwards to terminate the program. It works the same with
  220. stealth loggers (see L<Log::Log4perl/"Stealth Loggers">),
  221. all you need to do is call
  222. use Log::Log4perl qw(:easy);
  223. open FILE, "<blah" or LOGDIE "Can't open blah -- bailing out!";
  224. What can you do if you're using some library which doesn't use Log::Log4perl
  225. and calls C<die()> internally if something goes wrong? Use a
  226. C<$SIG{__DIE__}> pseudo signal handler
  227. use Log::Log4perl qw(get_logger);
  228. $SIG{__DIE__} = sub {
  229. if($^S) {
  230. # We're in an eval {} and don't want log
  231. # this message but catch it later
  232. return;
  233. }
  234. local $Log::Log4perl::caller_depth =
  235. $Log::Log4perl::caller_depth + 1;
  236. my $logger = get_logger("");
  237. $logger->fatal(@_);
  238. die @_; # Now terminate really
  239. };
  240. This will catch every C<die()>-Exception of your
  241. application or the modules it uses. In case you want to
  242. It
  243. will fetch a root logger and pass on the C<die()>-Message to it.
  244. If you make sure you've configured with a root logger like this:
  245. Log::Log4perl->init(\q{
  246. log4perl.category = FATAL, Logfile
  247. log4perl.appender.Logfile = Log::Log4perl::Appender::File
  248. log4perl.appender.Logfile.filename = fatal_errors.log
  249. log4perl.appender.Logfile.layout = \
  250. Log::Log4perl::Layout::PatternLayout
  251. log4perl.appender.Logfile.layout.ConversionPattern = %F{1}-%L (%M)> %m%n
  252. });
  253. then all C<die()> messages will be routed to a file properly. The line
  254. local $Log::Log4perl::caller_depth =
  255. $Log::Log4perl::caller_depth + 1;
  256. in the pseudo signal handler above merits a more detailed explanation. With
  257. the setup above, if a module calls C<die()> in one of its functions,
  258. the fatal message will be logged in the signal handler and not in the
  259. original function -- which will cause the %F, %L and %M placeholders
  260. in the pattern layout to be replaced by the filename, the line number
  261. and the function/method name of the signal handler, not the error-throwing
  262. module. To adjust this, Log::Log4perl has the C<$caller_depth> variable,
  263. which defaults to 0, but can be set to positive integer values
  264. to offset the caller level. Increasing
  265. it by one will cause it to log the calling function's parameters, not
  266. the ones of the signal handler.
  267. See L<Log::Log4perl/"Using Log::Log4perl from wrapper classes"> for more
  268. details.
  269. =head2 How can I hook up the LWP library with Log::Log4perl?
  270. Or, to put it more generally: How can you utilize a third-party
  271. library's embedded logging and debug statements in Log::Log4perl?
  272. How can you make them print
  273. to configurable appenders, turn them on and off, just as if they
  274. were regular Log::Log4perl logging statements?
  275. The easiest solution is to map the third-party library logging statements
  276. to Log::Log4perl's stealth loggers via a typeglob assignment.
  277. As an example, let's take LWP, one of the most popular Perl modules,
  278. which makes handling WWW requests and responses a breeze.
  279. Internally, LWP uses its own logging and debugging system,
  280. utilizing the following calls
  281. inside the LWP code (from the LWP::Debug man page):
  282. # Function tracing
  283. LWP::Debug::trace('send()');
  284. # High-granular state in functions
  285. LWP::Debug::debug('url ok');
  286. # Data going over the wire
  287. LWP::Debug::conns("read $n bytes: $data");
  288. First, let's assign Log::Log4perl priorities
  289. to these functions: I'd suggest that
  290. C<debug()> messages have priority C<INFO>,
  291. C<trace()> uses C<DEBUG> and C<conns()> also logs with C<DEBUG> --
  292. although your mileage may certainly vary.
  293. Now, in order to transparently hook up LWP::Debug with Log::Log4perl,
  294. all we have to do is say
  295. package LWP::Debug;
  296. use Log::Log4perl qw(:easy);
  297. *trace = *INFO;
  298. *conns = *DEBUG;
  299. *debug = *DEBUG;
  300. package main;
  301. # ... go on with your regular program ...
  302. at the beginning of our program. In this way, every time the, say,
  303. C<LWP::UserAgent> module calls C<LWP::Debug::trace()>, it will implicitly
  304. call INFO(), which is the C<info()> method of a stealth logger defined for
  305. the Log::Log4perl category C<LWP::Debug>. Is this cool or what?
  306. Here's a complete program:
  307. use LWP::UserAgent;
  308. use HTTP::Request::Common;
  309. use Log::Log4perl qw(:easy);
  310. Log::Log4perl->easy_init(
  311. { category => "LWP::Debug",
  312. level => $DEBUG,
  313. layout => "%r %p %M-%L %m%n",
  314. });
  315. package LWP::Debug;
  316. use Log::Log4perl qw(:easy);
  317. *trace = *INFO;
  318. *conns = *DEBUG;
  319. *debug = *DEBUG;
  320. package main;
  321. my $ua = LWP::UserAgent->new();
  322. my $resp = $ua->request(GET "http://amazon.com");
  323. if($resp->is_success()) {
  324. print "Success: Received ",
  325. length($resp->content()), "\n";
  326. } else {
  327. print "Error: ", $resp->code(), "\n";
  328. }
  329. This will generate the following output on STDERR:
  330. 174 INFO LWP::UserAgent::new-164 ()
  331. 208 INFO LWP::UserAgent::request-436 ()
  332. 211 INFO LWP::UserAgent::send_request-294 GET http://amazon.com
  333. 212 DEBUG LWP::UserAgent::_need_proxy-1123 Not proxied
  334. 405 INFO LWP::Protocol::http::request-122 ()
  335. 859 DEBUG LWP::Protocol::collect-206 read 233 bytes
  336. 863 DEBUG LWP::UserAgent::request-443 Simple response: Found
  337. 869 INFO LWP::UserAgent::request-436 ()
  338. 871 INFO LWP::UserAgent::send_request-294
  339. GET http://www.amazon.com:80/exec/obidos/gateway_redirect
  340. 872 DEBUG LWP::UserAgent::_need_proxy-1123 Not proxied
  341. 873 INFO LWP::Protocol::http::request-122 ()
  342. 1016 DEBUG LWP::UserAgent::request-443 Simple response: Found
  343. 1020 INFO LWP::UserAgent::request-436 ()
  344. 1022 INFO LWP::UserAgent::send_request-294
  345. GET http://www.amazon.com/exec/obidos/subst/home/home.html/
  346. 1023 DEBUG LWP::UserAgent::_need_proxy-1123 Not proxied
  347. 1024 INFO LWP::Protocol::http::request-122 ()
  348. 1382 DEBUG LWP::Protocol::collect-206 read 632 bytes
  349. ...
  350. 2605 DEBUG LWP::Protocol::collect-206 read 77 bytes
  351. 2607 DEBUG LWP::UserAgent::request-443 Simple response: OK
  352. Success: Received 42584
  353. Of course, in this way, the embedded logging and debug statements within
  354. LWP can be utilized in any Log::Log4perl way you can think of. You can
  355. have them sent to different appenders, block them based on the
  356. category and everything else Log::Log4perl has to offer.
  357. Only drawback of this method: Steering logging behavior via category
  358. is always based on the C<LWP::Debug> package. Although the logging
  359. statements reflect the package name of the issuing module properly,
  360. the stealth loggers in C<LWP::Debug> are all of the category C<LWP::Debug>.
  361. This implies that you can't control the logging behavior based on the
  362. package that's I<initiating> a log request (e.g. LWP::UserAgent) but only
  363. based on the package that's actually I<executing> the logging statement,
  364. C<LWP::Debug> in this case.
  365. To work around this conundrum, we need to write a wrapper function and
  366. plant it into the C<LWP::Debug> package. It will determine the caller and
  367. create a logger bound to a category with the same name as the caller's
  368. package:
  369. package LWP::Debug;
  370. use Log::Log4perl qw(:levels get_logger);
  371. sub l4p_wrapper {
  372. my($prio, @message) = @_;
  373. $Log::Log4perl::caller_depth += 2;
  374. get_logger(scalar caller(1))->log($prio, @message);
  375. $Log::Log4perl::caller_depth -= 2;
  376. }
  377. no warnings 'redefine';
  378. *trace = sub { l4p_wrapper($INFO, @_); };
  379. *debug = *conns = sub { l4p_wrapper($DEBUG, @_); };
  380. package main;
  381. # ... go on with your main program ...
  382. This is less performant than the previous approach, because every
  383. log request will request a reference to a logger first, then call
  384. the wrapper, which will in turn call the appropriate log function.
  385. This hierarchy shift has to be compensated for by increasing
  386. C<$Log::Log4perl::caller_depth> by 2 before calling the log function
  387. and decreasing it by 2 right afterwards. Also, the C<l4p_wrapper>
  388. function shown above calls C<caller(1)> which determines the name
  389. of the package I<two> levels down the calling hierarchy (and
  390. therefore compensates for both the wrapper function and the
  391. anonymous subroutine calling it).
  392. C<no warnings 'redefine'> suppresses a warning Perl would generate
  393. otherwise
  394. upon redefining C<LWP::Debug>'s C<trace()>, C<debug()> and C<conns()>
  395. functions. In case you use a perl prior to 5.6.x, you need
  396. to manipulate C<$^W> instead.
  397. To make things easy for you when dealing with LWP, Log::Log4perl 0.47
  398. introduces C<Log::Log4perl-E<gt>infiltrate_lwp()> which does exactly the
  399. above.
  400. =head2 What if I need dynamic values in a static Log4perl configuration file?
  401. Say, your application uses Log::Log4perl for logging and
  402. therefore comes with a Log4perl configuration file, specifying the logging
  403. behavior.
  404. But, you also want it to take command line parameters to set values
  405. like the name of the log file.
  406. How can you have
  407. both a static Log4perl configuration file and a dynamic command line
  408. interface?
  409. As of Log::Log4perl 0.28, every value in the configuration file
  410. can be specified as a I<Perl hook>. So, instead of saying
  411. log4perl.appender.Logfile.filename = test.log
  412. you could just as well have a Perl subroutine deliver the value
  413. dynamically:
  414. log4perl.appender.Logfile.filename = sub { logfile(); };
  415. given that C<logfile()> is a valid function in your C<main> package
  416. returning a string containing the path to the log file.
  417. Or, think about using the value of an environment variable:
  418. log4perl.appender.DBI.user = sub { $ENV{USERNAME} };
  419. When C<Log::Log4perl-E<gt>init()> parses the configuration
  420. file, it will notice the assignment above because of its
  421. C<sub {...}> pattern and treat it in a special way:
  422. It will evaluate the subroutine (which can contain
  423. arbitrary Perl code) and take its return value as the right side
  424. of the assignment.
  425. A typical application would be called like this on the command line:
  426. app # log file is "test.log"
  427. app -l mylog.txt # log file is "mylog.txt"
  428. Here's some sample code implementing the command line interface above:
  429. use Log::Log4perl qw(get_logger);
  430. use Getopt::Std;
  431. getopt('l:', \our %OPTS);
  432. my $conf = q(
  433. log4perl.category.Bar.Twix = WARN, Logfile
  434. log4perl.appender.Logfile = Log::Log4perl::Appender::File
  435. log4perl.appender.Logfile.filename = sub { logfile(); };
  436. log4perl.appender.Logfile.layout = SimpleLayout
  437. );
  438. Log::Log4perl::init(\$conf);
  439. my $logger = get_logger("Bar::Twix");
  440. $logger->error("Blah");
  441. ###########################################
  442. sub logfile {
  443. ###########################################
  444. if(exists $OPTS{l}) {
  445. return $OPTS{l};
  446. } else {
  447. return "test.log";
  448. }
  449. }
  450. Every Perl hook may contain arbitrary perl code,
  451. just make sure to fully qualify eventual variable names
  452. (e.g. C<%main::OPTS> instead of C<%OPTS>).
  453. B<SECURITY NOTE>: this feature means arbitrary perl code
  454. can be embedded in the config file. In the rare case
  455. where the people who have access to your config file
  456. are different from the people who write your code and
  457. shouldn't have execute rights, you might want to call
  458. $Log::Log4perl::Config->allow_code(0);
  459. before you call init(). This will prevent Log::Log4perl from
  460. executing I<any> Perl code in the config file (including
  461. code for custom conversion specifiers
  462. (see L<Log::Log4perl::Layout::PatternLayout/"Custom cspecs">).
  463. =head2 How can I roll over my logfiles automatically at midnight?
  464. Long-running applications tend to produce ever-increasing logfiles.
  465. For backup and cleanup purposes, however, it is often desirable to move
  466. the current logfile to a different location from time to time and
  467. start writing a new one.
  468. This is a non-trivial task, because it has to happen in sync with
  469. the logging system in order not to lose any messages in the process.
  470. Luckily, I<Mark Pfeiffer>'s C<Log::Dispatch::FileRotate> appender
  471. works well with Log::Log4perl to rotate your logfiles in a variety of ways.
  472. Note, however, that having the application deal with rotating a log
  473. file is not cheap. Among other things, it requires locking the log file
  474. with every write to avoid race conditions.
  475. There are good reasons to use external rotators like C<newsyslog>
  476. instead.
  477. See the entry C<How can I rotate a logfile with newsyslog?> in the
  478. FAQ for more information on how to configure it.
  479. When using C<Log::Dispatch::FileRotate>,
  480. all you have to do is specify it in your Log::Log4perl configuration file
  481. and your logfiles will be rotated automatically.
  482. You can choose between rolling based on a maximum size ("roll if greater
  483. than 10 MB") or based on a date pattern ("roll everyday at midnight").
  484. In both cases, C<Log::Dispatch::FileRotate> allows you to define a
  485. number C<max> of saved files to keep around until it starts overwriting
  486. the oldest ones. If you set the C<max> parameter to 2 and the name of
  487. your logfile is C<test.log>, C<Log::Dispatch::FileRotate> will
  488. move C<test.log> to C<test.log.1> on the first rollover. On the second
  489. rollover, it will move C<test.log.1> to C<test.log.2> and then C<test.log>
  490. to C<test.log.1>. On the third rollover, it will move C<test.log.1> to
  491. C<test.log.2> (therefore discarding the old C<test.log.2>) and
  492. C<test.log> to C<test.log.1>. And so forth. This way, there's always
  493. going to be a maximum of 2 saved log files around.
  494. Here's an example of a Log::Log4perl configuration file, defining a
  495. daily rollover at midnight (date pattern C<yyyy-MM-dd>), keeping
  496. a maximum of 5 saved logfiles around:
  497. log4perl.category = WARN, Logfile
  498. log4perl.appender.Logfile = Log::Dispatch::FileRotate
  499. log4perl.appender.Logfile.filename = test.log
  500. log4perl.appender.Logfile.max = 5
  501. log4perl.appender.Logfile.DatePattern = yyyy-MM-dd
  502. log4perl.appender.Logfile.TZ = PST
  503. log4perl.appender.Logfile.layout = \
  504. Log::Log4perl::Layout::PatternLayout
  505. log4perl.appender.Logfile.layout.ConversionPattern = %d %m %n
  506. Please see the C<Log::Dispatch::FileRotate> documentation for details.
  507. C<Log::Dispatch::FileRotate> is available on CPAN.
  508. =head2 What's the easiest way to turn off all logging, even with a lengthy Log4perl configuration file?
  509. In addition to category-based levels and appender thresholds,
  510. Log::Log4perl supports system-wide logging thresholds. This is the
  511. minimum level the system will require of any logging events in order for them
  512. to make it through to any configured appenders.
  513. For example, putting the line
  514. log4perl.threshold = ERROR
  515. anywhere in your configuration file will limit any output to any appender
  516. to events with priority of ERROR or higher (ERROR or FATAL that is).
  517. However, in order to suppress all logging entirely, you need to use a
  518. priority that's higher than FATAL: It is simply called C<OFF>, and it is never
  519. used by any logger. By definition, it is higher than the highest
  520. defined logger level.
  521. Therefore, if you keep the line
  522. log4perl.threshold = OFF
  523. somewhere in your Log::Log4perl configuration, the system will be quiet
  524. as a graveyard. If you deactivate the line (e.g. by commenting it out),
  525. the system will, upon config reload, snap back to normal operation, providing
  526. logging messages according to the rest of the configuration file again.
  527. =head2 How can I log DEBUG and above to the screen and INFO and above to a file?
  528. You need one logger with two appenders attached to it:
  529. log4perl.logger = DEBUG, Screen, File
  530. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  531. log4perl.appender.Screen.layout = SimpleLayout
  532. log4perl.appender.File = Log::Log4perl::Appender::File
  533. log4perl.appender.File.filename = test.log
  534. log4perl.appender.File.layout = SimpleLayout
  535. log4perl.appender.Screen.Threshold = INFO
  536. Since the file logger isn't supposed to get any messages with a priority
  537. less than INFO, the appender's C<Threshold> setting blocks those out,
  538. although the logger forwards them.
  539. It's a common mistake to think you can define two loggers for this, but
  540. it won't work unless those two loggers have different categories. If you
  541. wanted to log all DEBUG and above messages from the Foo::Bar module to a file
  542. and all INFO and above messages from the Quack::Schmack module to the
  543. screen, then you could have defined two loggers with different levels
  544. C<log4perl.logger.Foo.Bar> (level INFO)
  545. and C<log4perl.logger.Quack.Schmack> (level DEBUG) and assigned the file
  546. appender to the former and the screen appender to the latter. But what we
  547. wanted to accomplish was to route all messages, regardless of which module
  548. (or category) they came from, to both appenders. The only
  549. way to accomplish this is to define the root logger with the lower
  550. level (DEBUG), assign both appenders to it, and block unwanted messages at
  551. the file appender (C<Threshold> set to INFO).
  552. =head2 I keep getting duplicate log messages! What's wrong?
  553. Having several settings for related categories in the Log4perl
  554. configuration file sometimes leads to a phenomenon called
  555. "message duplication". It can be very confusing at first,
  556. but if thought through properly, it turns out that Log4perl behaves
  557. as advertised. But, don't despair, of course there's a number of
  558. ways to avoid message duplication in your logs.
  559. Here's a sample Log4perl configuration file that produces the
  560. phenomenon:
  561. log4perl.logger.Cat = ERROR, Screen
  562. log4perl.logger.Cat.Subcat = WARN, Screen
  563. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  564. log4perl.appender.Screen.layout = SimpleLayout
  565. It defines two loggers, one for category C<Cat> and one for
  566. C<Cat::Subcat>, which is obviously a subcategory of C<Cat>.
  567. The parent logger has a priority setting of ERROR, the child
  568. is set to the lower C<WARN> level.
  569. Now imagine the following code in your program:
  570. my $logger = get_logger("Cat.Subcat");
  571. $logger->warn("Warning!");
  572. What do you think will happen? An unexperienced Log4perl user
  573. might think: "Well, the message is being sent with level WARN, so the
  574. C<Cat::Subcat> logger will accept it and forward it to the
  575. attached C<Screen> appender. Then, the message will percolate up
  576. the logger hierarchy, find
  577. the C<Cat> logger, which will suppress the message because of its
  578. ERROR setting."
  579. But, perhaps surprisingly, what you'll get with the
  580. code snippet above is not one but two log messages written
  581. to the screen:
  582. WARN - Warning!
  583. WARN - Warning!
  584. What happened? The culprit is that once the logger C<Cat::Subcat>
  585. decides to fire, it will forward the message I<unconditionally>
  586. to all directly or indirectly attached appenders. The C<Cat> logger
  587. will never be asked if it wants the message or not -- the message
  588. will just be pushed through to the appender attached to C<Cat>.
  589. One way to prevent the message from bubbling up the logger
  590. hierarchy is to set the C<additivity> flag of the subordinate logger to
  591. C<0>:
  592. log4perl.logger.Cat = ERROR, Screen
  593. log4perl.logger.Cat.Subcat = WARN, Screen
  594. log4perl.additivity.Cat.Subcat = 0
  595. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  596. log4perl.appender.Screen.layout = SimpleLayout
  597. The message will now be accepted by the C<Cat::Subcat> logger,
  598. forwarded to its appender, but then C<Cat::Subcat> will suppress
  599. any further action. While this setting avoids duplicate messages
  600. as seen before, it is often not the desired behavior. Messages
  601. percolating up the hierarchy are a useful Log4perl feature.
  602. If you're defining I<different> appenders for the two loggers,
  603. one other option is to define an appender threshold for the
  604. higher-level appender. Typically it is set to be
  605. equal to the logger's level setting:
  606. log4perl.logger.Cat = ERROR, Screen1
  607. log4perl.logger.Cat.Subcat = WARN, Screen2
  608. log4perl.appender.Screen1 = Log::Log4perl::Appender::Screen
  609. log4perl.appender.Screen1.layout = SimpleLayout
  610. log4perl.appender.Screen1.Threshold = ERROR
  611. log4perl.appender.Screen2 = Log::Log4perl::Appender::Screen
  612. log4perl.appender.Screen2.layout = SimpleLayout
  613. Since the C<Screen1> appender now blocks every message with
  614. a priority less than ERROR, even if the logger in charge
  615. lets it through, the message percolating up the hierarchy is
  616. being blocked at the last minute and I<not> appended to C<Screen1>.
  617. So far, we've been operating well within the boundaries of the
  618. Log4j standard, which Log4perl adheres to. However, if
  619. you would really, really like to use a single appender
  620. and keep the message percolation intact without having to deal
  621. with message duplication, there's a non-standard solution for you:
  622. log4perl.logger.Cat = ERROR, Screen
  623. log4perl.logger.Cat.Subcat = WARN, Screen
  624. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  625. log4perl.appender.Screen.layout = SimpleLayout
  626. log4perl.oneMessagePerAppender = 1
  627. The C<oneMessagePerAppender> flag will suppress duplicate messages
  628. to the same appender. Again, that's non-standard. But way cool :).
  629. =head2 How can I configure Log::Log4perl to send me email if something happens?
  630. Some incidents require immediate action. You can't wait until someone
  631. checks the log files, you need to get notified on your pager right away.
  632. The easiest way to do that is by using the C<Log::Dispatch::Email::MailSend>
  633. module as an appender. It comes with the C<Log::Dispatch> bundle and
  634. allows you to specify recipient and subject of outgoing emails in the Log4perl
  635. configuration file:
  636. log4perl.category = FATAL, Mailer
  637. log4perl.appender.Mailer = Log::Dispatch::Email::MailSend
  638. log4perl.appender.Mailer.to = drone@pageme.net
  639. log4perl.appender.Mailer.subject = Something's broken!
  640. log4perl.appender.Mailer.layout = SimpleLayout
  641. The message of every log incident this appender gets
  642. will then be forwarded to the given
  643. email address. Check the C<Log::Dispatch::Email::MailSend> documentation
  644. for details. And please make sure there's not a flood of email messages
  645. sent out by your application, filling up the recipient's inbox.
  646. There's one caveat you need to know about: The C<Log::Dispatch::Email>
  647. hierarchy of appenders turns on I<buffering> by default. This means that
  648. the appender will not send out messages right away but wait until a
  649. certain threshold has been reached. If you'd rather have your alerts
  650. sent out immediately, use
  651. log4perl.appender.Mailer.buffered = 0
  652. to turn buffering off.
  653. =head2 How can I write my own appender?
  654. First off, Log::Log4perl comes with a set of standard appenders. Then,
  655. there's a lot of Log4perl-compatible appenders already
  656. available on CPAN: Just run a search for C<Log::Dispatch> on
  657. http://search.cpan.org and chances are that what you're looking for
  658. has already been developed, debugged and been used successfully
  659. in production -- no need for you to reinvent the wheel.
  660. Also, Log::Log4perl ships with a nifty database appender named
  661. Log::Log4perl::Appender::DBI -- check it out if talking to databases is your
  662. desire.
  663. But if you're up for a truly exotic task, you might have to write
  664. an appender yourself. That's very easy -- it takes no longer
  665. than a couple of minutes.
  666. Say, we wanted to create an appender of the class
  667. C<ColorScreenAppender>, which logs messages
  668. to the screen in a configurable color. Just create a new class
  669. in C<ColorScreenAppender.pm>:
  670. package ColorScreenAppender;
  671. Now let's assume that your Log::Log4perl
  672. configuration file C<test.conf> looks like this:
  673. log4perl.logger = INFO, ColorApp
  674. log4perl.appender.ColorApp=ColorScreenAppender
  675. log4perl.appender.ColorApp.color=blue
  676. log4perl.appender.ColorApp.layout = PatternLayout
  677. log4perl.appender.ColorApp.layout.ConversionPattern=%d %m %n
  678. This will cause Log::Log4perl on C<init()> to look for a class
  679. ColorScreenAppender and call its constructor new(). Let's add
  680. new() to ColorScreenAppender.pm:
  681. sub new {
  682. my($class, %options) = @_;
  683. my $self = { %options };
  684. bless $self, $class;
  685. return $self;
  686. }
  687. To initialize this appender, Log::Log4perl will call
  688. and pass all attributes of the appender as defined in the configuration
  689. file to the constructor as name/value pairs (in this case just one):
  690. ColorScreenAppender->new(color => "blue");
  691. The new() method listed above stores the contents of the
  692. %options hash in the object's
  693. instance data hash (referred to by $self).
  694. That's all for initializing a new appender with Log::Log4perl.
  695. Second, ColorScreenAppender needs to expose a
  696. C<log()> method, which will be called by Log::Log4perl
  697. every time it thinks the appender should fire. Along with the
  698. object reference (as usual in Perl's object world), log()
  699. will receive a list of name/value pairs, of which only the one
  700. under the key C<message> shall be of interest for now since it is the
  701. message string to be logged. At this point, Log::Log4perl has already taken
  702. care of joining the message to be a single string.
  703. For our special appender ColorScreenAppender, we're using the
  704. Term::ANSIColor module to colorize the output:
  705. use Term::ANSIColor;
  706. sub log {
  707. my($self, %params) = @_;
  708. print colored($params{message},
  709. $self->{color});
  710. }
  711. The color (as configured in the Log::Log4perl configuration file)
  712. is available as $self-E<gt>{color} in the appender object. Don't
  713. forget to return
  714. 1;
  715. at the end of ColorScreenAppender.pm and you're done. Install the new appender
  716. somewhere where perl can find it and try it with a test script like
  717. use Log::Log4perl qw(:easy);
  718. Log::Log4perl->init("test.conf");
  719. ERROR("blah");
  720. to see the new colored output. Is this cool or what?
  721. And it gets even better: You can write dynamically generated appender
  722. classes using the C<Class::Prototyped> module. Here's an example of
  723. an appender prepending every outgoing message with a configurable
  724. number of bullets:
  725. use Class::Prototyped;
  726. my $class = Class::Prototyped->newPackage(
  727. "MyAppenders::Bulletizer",
  728. bullets => 1,
  729. log => sub {
  730. my($self, %params) = @_;
  731. print "*" x $self->bullets(),
  732. $params{message};
  733. },
  734. );
  735. use Log::Log4perl qw(:easy);
  736. Log::Log4perl->init(\ q{
  737. log4perl.logger = INFO, Bully
  738. log4perl.appender.Bully=MyAppenders::Bulletizer
  739. log4perl.appender.Bully.bullets=3
  740. log4perl.appender.Bully.layout = PatternLayout
  741. log4perl.appender.Bully.layout.ConversionPattern=%m %n
  742. });
  743. # ... prints: "***Boo!\n";
  744. INFO "Boo!";
  745. =head2 How can I drill down on references before logging them?
  746. If you've got a reference to a nested structure or object, then
  747. you probably don't want to log it as C<HASH(0x81141d4)> but rather
  748. dump it as something like
  749. $VAR1 = {
  750. 'a' => 'b',
  751. 'd' => 'e'
  752. };
  753. via a module like Data::Dumper. While it's syntactically correct to say
  754. $logger->debug(Data::Dumper::Dumper($ref));
  755. this call imposes a huge performance penalty on your application
  756. if the message is suppressed by Log::Log4perl, because Data::Dumper
  757. will perform its expensive operations in any case, because it doesn't
  758. know that its output will be thrown away immediately.
  759. As of Log::Log4perl 0.28, there's a better way: Use the
  760. message output filter format as in
  761. $logger->debug( {filter => \&Data::Dumper::Dumper,
  762. value => $ref} );
  763. and Log::Log4perl won't call the filter function unless the message really
  764. gets written out to an appender. Just make sure to pass the whole slew as a
  765. reference to a hash specifying a filter function (as a sub reference)
  766. under the key C<filter> and the value to be passed to the filter function in
  767. C<value>).
  768. When it comes to logging, Log::Log4perl will call the filter function,
  769. pass the C<value> as an argument and log the return value.
  770. Saves you serious cycles.
  771. =head2 How can I collect all FATAL messages in an extra log file?
  772. Suppose you have employed Log4perl all over your system and you've already
  773. activated logging in various subsystems. On top of that, without disrupting
  774. any other settings, how can you collect all FATAL messages all over the system
  775. and send them to a separate log file?
  776. If you define a root logger like this:
  777. log4perl.logger = FATAL, File
  778. log4perl.appender.File = Log::Log4perl::Appender::File
  779. log4perl.appender.File.filename = /tmp/fatal.txt
  780. log4perl.appender.File.layout = PatternLayout
  781. log4perl.appender.File.layout.ConversionPattern= %d %m %n
  782. # !!! Something's missing ...
  783. you'll be surprised to not only receive all FATAL messages
  784. issued anywhere in the system,
  785. but also everything else -- gazillions of
  786. ERROR, WARN, INFO and even DEBUG messages will end up in
  787. your fatal.txt logfile!
  788. Reason for this is Log4perl's (or better: Log4j's) appender additivity.
  789. Once a
  790. lower-level logger decides to fire, the message is going to be forwarded
  791. to all appenders upstream -- without further priority checks with their
  792. attached loggers.
  793. There's a way to prevent this, however: If your appender defines a
  794. minimum threshold, only messages of this priority or higher are going
  795. to be logged. So, just add
  796. log4perl.appender.File.Threshold = FATAL
  797. to the configuration above, and you'll get what you wanted in the
  798. first place: An overall system FATAL message collector.
  799. =head2 How can I bundle several log messages into one?
  800. Would you like to tally the messages arriving at your appender and
  801. dump out a summary once they're exceeding a certain threshold?
  802. So that something like
  803. $logger->error("Blah");
  804. $logger->error("Blah");
  805. $logger->error("Blah");
  806. won't be logged as
  807. Blah
  808. Blah
  809. Blah
  810. but as
  811. [3] Blah
  812. instead? If you'd like to hold off on logging a message until it has been
  813. sent a couple of times, you can roll that out by creating a buffered
  814. appender.
  815. Let's define a new appender like
  816. package TallyAppender;
  817. sub new {
  818. my($class, %options) = @_;
  819. my $self = { maxcount => 5,
  820. %options
  821. };
  822. bless $self, $class;
  823. $self->{last_message} = "";
  824. $self->{last_message_count} = 0;
  825. return $self;
  826. }
  827. with two additional instance variables C<last_message> and
  828. C<last_message_count>, storing the content of the last message sent
  829. and a counter of how many times this has happened. Also, it features
  830. a configuration parameter C<maxcount> which defaults to 5 in the
  831. snippet above but can be set in the Log4perl configuration file like this:
  832. log4perl.logger = INFO, A
  833. log4perl.appender.A=TallyAppender
  834. log4perl.appender.A.maxcount = 3
  835. The main tallying logic lies in the appender's C<log> method,
  836. which is called every time Log4perl thinks a message needs to get logged
  837. by our appender:
  838. sub log {
  839. my($self, %params) = @_;
  840. # Message changed? Print buffer.
  841. if($self->{last_message} and
  842. $params{message} ne $self->{last_message}) {
  843. print "[$self->{last_message_count}]: " .
  844. "$self->{last_message}";
  845. $self->{last_message_count} = 1;
  846. $self->{last_message} = $params{message};
  847. return;
  848. }
  849. $self->{last_message_count}++;
  850. $self->{last_message} = $params{message};
  851. # Threshold exceeded? Print, reset counter
  852. if($self->{last_message_count} >=
  853. $self->{maxcount}) {
  854. print "[$self->{last_message_count}]: " .
  855. "$params{message}";
  856. $self->{last_message_count} = 0;
  857. $self->{last_message} = "";
  858. return;
  859. }
  860. }
  861. We basically just check if the oncoming message in C<$param{message}>
  862. is equal to what we've saved before in the C<last_message> instance
  863. variable. If so, we're increasing C<last_message_count>.
  864. We print the message in two cases: If the new message is different
  865. than the buffered one, because then we need to dump the old stuff
  866. and store the new. Or, if the counter exceeds the threshold, as
  867. defined by the C<maxcount> configuration parameter.
  868. Please note that the appender always gets the fully rendered message and
  869. just compares it as a whole -- so if there's a date/timestamp in there,
  870. that might confuse your logic. You can work around this by specifying
  871. %m %n as a layout and add the date later on in the appender. Or, make
  872. the comparison smart enough to omit the date.
  873. At last, don't forget what happens if the program is being shut down.
  874. If there's still messages in the buffer, they should be printed out
  875. at that point. That's easy to do in the appender's DESTROY method,
  876. which gets called at object destruction time:
  877. sub DESTROY {
  878. my($self) = @_;
  879. if($self->{last_message_count}) {
  880. print "[$self->{last_message_count}]: " .
  881. "$self->{last_message}";
  882. return;
  883. }
  884. }
  885. This will ensure that none of the buffered messages are lost.
  886. Happy buffering!
  887. =head2 I want to log ERROR and WARN messages to different files! How can I do that?
  888. Let's assume you wanted to have each logging statement written to a
  889. different file, based on the statement's priority. Messages with priority
  890. C<WARN> are supposed to go to C</tmp/app.warn>, events prioritized
  891. as C<ERROR> should end up in C</tmp/app.error>.
  892. Now, if you define two appenders C<AppWarn> and C<AppError>
  893. and assign them both to the root logger,
  894. messages bubbling up from any loggers below will be logged by both
  895. appenders because of Log4perl's message propagation feature. If you limit
  896. their exposure via the appender threshold mechanism and set
  897. C<AppWarn>'s threshold to C<WARN> and C<AppError>'s to C<ERROR>, you'll
  898. still get C<ERROR> messages in C<AppWarn>, because C<AppWarn>'s C<WARN>
  899. setting will just filter out messages with a I<lower> priority than
  900. C<WARN> -- C<ERROR> is higher and will be allowed to pass through.
  901. What we need for this is a Log4perl I<Custom Filter>, available with
  902. Log::Log4perl 0.30.
  903. Both appenders need to verify that
  904. the priority of the oncoming messages exactly I<matches> the priority
  905. the appender is supposed to log messages of. To accomplish this task,
  906. let's define two custom filters, C<MatchError> and C<MatchWarn>, which,
  907. when attached to their appenders, will limit messages passed on to them
  908. to those matching a given priority:
  909. log4perl.logger = WARN, AppWarn, AppError
  910. # Filter to match level ERROR
  911. log4perl.filter.MatchError = Log::Log4perl::Filter::LevelMatch
  912. log4perl.filter.MatchError.LevelToMatch = ERROR
  913. log4perl.filter.MatchError.AcceptOnMatch = true
  914. # Filter to match level WARN
  915. log4perl.filter.MatchWarn = Log::Log4perl::Filter::LevelMatch
  916. log4perl.filter.MatchWarn.LevelToMatch = WARN
  917. log4perl.filter.MatchWarn.AcceptOnMatch = true
  918. # Error appender
  919. log4perl.appender.AppError = Log::Log4perl::Appender::File
  920. log4perl.appender.AppError.filename = /tmp/app.err
  921. log4perl.appender.AppError.layout = SimpleLayout
  922. log4perl.appender.AppError.Filter = MatchError
  923. # Warning appender
  924. log4perl.appender.AppWarn = Log::Log4perl::Appender::File
  925. log4perl.appender.AppWarn.filename = /tmp/app.warn
  926. log4perl.appender.AppWarn.layout = SimpleLayout
  927. log4perl.appender.AppWarn.Filter = MatchWarn
  928. The appenders C<AppWarn> and C<AppError> defined above are logging to C</tmp/app.warn> and
  929. C</tmp/app.err> respectively and have the custom filters C<MatchWarn> and C<MatchError>
  930. attached.
  931. This setup will direct all WARN messages, issued anywhere in the system, to /tmp/app.warn (and
  932. ERROR messages to /tmp/app.error) -- without any overlaps.
  933. =head2 On our server farm, Log::Log4perl configuration files differ slightly from host to host. Can I roll them all into one?
  934. You sure can, because Log::Log4perl allows you to specify attribute values
  935. dynamically. Let's say that one of your appenders expects the host's IP address
  936. as one of its attributes. Now, you could certainly roll out different
  937. configuration files for every host and specify the value like
  938. log4perl.appender.MyAppender = Log::Log4perl::Appender::SomeAppender
  939. log4perl.appender.MyAppender.ip = 10.0.0.127
  940. but that's a maintenance nightmare. Instead, you can have Log::Log4perl
  941. figure out the IP address at configuration time and set the appender's
  942. value correctly:
  943. # Set the IP address dynamically
  944. log4perl.appender.MyAppender = Log::Log4perl::Appender::SomeAppender
  945. log4perl.appender.MyAppender.ip = sub { \
  946. use Sys::Hostname; \
  947. use Socket; \
  948. return inet_ntoa(scalar gethostbyname hostname); \
  949. }
  950. If Log::Log4perl detects that an attribute value starts with something like
  951. C<"sub {...">, it will interpret it as a perl subroutine which is to be executed
  952. once at configuration time (not runtime!) and its return value is
  953. to be used as the attribute value. This comes in handy
  954. for rolling out applications where Log::Log4perl configuration files
  955. show small host-specific differences, because you can deploy the unmodified
  956. application distribution on all instances of the server farm.
  957. =head2 Log4perl doesn't interpret my backslashes correctly!
  958. If you're using Log4perl's feature to specify the configuration as a
  959. string in your program (as opposed to a separate configuration file),
  960. chances are that you've written it like this:
  961. # *** WRONG! ***
  962. Log::Log4perl->init( \ <<END_HERE);
  963. log4perl.logger = WARN, A1
  964. log4perl.appender.A1 = Log::Log4perl::Appender::Screen
  965. log4perl.appender.A1.layout = \
  966. Log::Log4perl::Layout::PatternLayout
  967. log4perl.appender.A1.layout.ConversionPattern = %m%n
  968. END_HERE
  969. # *** WRONG! ***
  970. and you're getting the following error message:
  971. Layout not specified for appender A1 at .../Config.pm line 342.
  972. What's wrong? The problem is that you're using a here-document with
  973. substitution enabled (C<E<lt>E<lt>END_HERE>) and that Perl won't
  974. interpret backslashes at line-ends as continuation characters but
  975. will essentially throw them out. So, in the code above, the layout line
  976. will look like
  977. log4perl.appender.A1.layout =
  978. to Log::Log4perl which causes it to report an error. To interpret the backslash
  979. at the end of the line correctly as a line-continuation character, use
  980. the non-interpreting mode of the here-document like in
  981. # *** RIGHT! ***
  982. Log::Log4perl->init( \ <<'END_HERE');
  983. log4perl.logger = WARN, A1
  984. log4perl.appender.A1 = Log::Log4perl::Appender::Screen
  985. log4perl.appender.A1.layout = \
  986. Log::Log4perl::Layout::PatternLayout
  987. log4perl.appender.A1.layout.ConversionPattern = %m%n
  988. END_HERE
  989. # *** RIGHT! ***
  990. (note the single quotes around C<'END_HERE'>) or use C<q{...}>
  991. instead of a here-document and Perl will treat the backslashes at
  992. line-end as intended.
  993. =head2 I want to suppress certain messages based on their content!
  994. Let's assume you've plastered all your functions with Log4perl
  995. statements like
  996. sub some_func {
  997. INFO("Begin of function");
  998. # ... Stuff happens here ...
  999. INFO("End of function");
  1000. }
  1001. to issue two log messages, one at the beginning and one at the end of
  1002. each function. Now you want to suppress the message at the beginning
  1003. and only keep the one at the end, what can you do? You can't use the category
  1004. mechanism, because both messages are issued from the same package.
  1005. Log::Log4perl's custom filters (0.30 or better) provide an interface for the
  1006. Log4perl user to step in right before a message gets logged and decide if
  1007. it should be written out or suppressed, based on the message content or other
  1008. parameters:
  1009. use Log::Log4perl qw(:easy);
  1010. Log::Log4perl::init( \ <<'EOT' );
  1011. log4perl.logger = INFO, A1
  1012. log4perl.appender.A1 = Log::Log4perl::Appender::Screen
  1013. log4perl.appender.A1.layout = \
  1014. Log::Log4perl::Layout::PatternLayout
  1015. log4perl.appender.A1.layout.ConversionPattern = %m%n
  1016. log4perl.filter.M1 = Log::Log4perl::Filter::StringMatch
  1017. log4perl.filter.M1.StringToMatch = Begin
  1018. log4perl.filter.M1.AcceptOnMatch = false
  1019. log4perl.appender.A1.Filter = M1
  1020. EOT
  1021. The last four statements in the configuration above are defining a custom
  1022. filter C<M1> of type C<Log::Log4perl::Filter::StringMatch>, which comes with
  1023. Log4perl right out of the box and allows you to define a text pattern to match
  1024. (as a perl regular expression) and a flag C<AcceptOnMatch> indicating
  1025. if a match is supposed to suppress the message or let it pass through.
  1026. The last line then assigns this filter to the C<A1> appender, which will
  1027. call it every time it receives a message to be logged and throw all
  1028. messages out I<not> matching the regular expression C<Begin>.
  1029. Instead of using the standard C<Log::Log4perl::Filter::StringMatch> filter,
  1030. you can define your own, simply using a perl subroutine:
  1031. log4perl.filter.ExcludeBegin = sub { !/Begin/ }
  1032. log4perl.appender.A1.Filter = ExcludeBegin
  1033. For details on custom filters, check L<Log::Log4perl::Filter>.
  1034. =head2 My new module uses Log4perl -- but what happens if the calling program didn't configure it?
  1035. If a Perl module uses Log::Log4perl, it will typically rely on the
  1036. calling program to initialize it. If it is using Log::Log4perl in C<:easy>
  1037. mode, like in
  1038. package MyMod;
  1039. use Log::Log4perl qw(:easy);
  1040. sub foo {
  1041. DEBUG("In foo");
  1042. }
  1043. 1;
  1044. and the calling program doesn't initialize Log::Log4perl at all (e.g. because
  1045. it has no clue that it's available), Log::Log4perl will silently
  1046. ignore all logging messages. However, if the module is using Log::Log4perl
  1047. in regular mode like in
  1048. package MyMod;
  1049. use Log::Log4perl qw(get_logger);
  1050. sub foo {
  1051. my $logger = get_logger("");
  1052. $logger->debug("blah");
  1053. }
  1054. 1;
  1055. and the main program is just using the module like in
  1056. use MyMode;
  1057. MyMode::foo();
  1058. then Log::Log4perl will also ignore all logging messages but
  1059. issue a warning like
  1060. Log4perl: Seems like no initialization happened.
  1061. Forgot to call init()?
  1062. (only once!) to remind novice users to not forget to initialize
  1063. the logging system before using it.
  1064. However, if you want to suppress this message, just
  1065. add the C<:nowarn> target to the module's C<use Log::Log4perl> call:
  1066. use Log::Log4perl qw(get_logger :nowarn);
  1067. This will have Log::Log4perl silently ignore all logging statements if
  1068. no initialization has taken place. If, instead of using init(), you're
  1069. using Log4perl's API to define loggers and appenders, the same
  1070. notification happens if no call to add_appenders() is made, i.e. no
  1071. appenders are defined.
  1072. If the module wants to figure out if some other program part has
  1073. already initialized Log::Log4perl, it can do so by calling
  1074. Log::Log4perl::initialized()
  1075. which will return a true value in case Log::Log4perl has been initialized
  1076. and a false value if not.
  1077. =head2 How can I synchronize access to an appender?
  1078. If you're using the same instance of an appender in multiple processes,
  1079. and each process is passing on messages to the appender in parallel,
  1080. you might end up with overlapping log entries.
  1081. Typical scenarios include a file appender that you create in the main
  1082. program, and which will then be shared between the parent and a
  1083. forked child process. Or two separate processes, each initializing a
  1084. Log4perl file appender on the same logfile.
  1085. Log::Log4perl won't synchronize access to the shared logfile by
  1086. default. Depending on your operating system's flush mechanism,
  1087. buffer size and the size of your messages, there's a small chance of
  1088. an overlap.
  1089. The easiest way to prevent overlapping messages in logfiles written to
  1090. by multiple processes is setting the
  1091. file appender's C<syswrite> flag along with a file write mode of C<"append">.
  1092. This makes sure that
  1093. C<Log::Log4perl::Appender::File> uses C<syswrite()> (which is guaranteed
  1094. to run uninterrupted) instead of C<print()> which might buffer
  1095. the message or get interrupted by the OS while it is writing. And in
  1096. C<"append"> mode, the OS kernel ensures that multiple processes share
  1097. one end-of-file marker, ensuring that each process writes to the I<real>
  1098. end of the file. (The value of C<"append">
  1099. for the C<mode> parameter is the default setting in Log4perl's file
  1100. appender so you don't have to set it explicitly.)
  1101. # Guarantees atomic writes
  1102. log4perl.category.Bar.Twix = WARN, Logfile
  1103. log4perl.appender.Logfile = Log::Log4perl::Appender::File
  1104. log4perl.appender.Logfile.mode = append
  1105. log4perl.appender.Logfile.syswrite = 1
  1106. log4perl.appender.Logfile.filename = test.log
  1107. log4perl.appender.Logfile.layout = SimpleLayout
  1108. Another guaranteed way of having messages separated with any kind of
  1109. appender is putting a Log::Log4perl::Appender::Synchronized composite
  1110. appender in between Log::Log4perl and the real appender. It will make
  1111. sure to let messages pass through this virtual gate one by one only.
  1112. Here's a sample configuration to synchronize access to a file appender:
  1113. log4perl.category.Bar.Twix = WARN, Syncer
  1114. log4perl.appender.Logfile = Log::Log4perl::Appender::File
  1115. log4perl.appender.Logfile.autoflush = 1
  1116. log4perl.appender.Logfile.filename = test.log
  1117. log4perl.appender.Logfile.layout = SimpleLayout
  1118. log4perl.appender.Syncer = Log::Log4perl::Appender::Synchronized
  1119. log4perl.appender.Syncer.appender = Logfile
  1120. C<Log::Log4perl::Appender::Synchronized> uses
  1121. the C<IPC::Shareable> module and its semaphores, which will slow down writing
  1122. the log messages, but ensures sequential access featuring atomic checks.
  1123. Check L<Log::Log4perl::Appender::Synchronized> for details.
  1124. =head2 Can I use Log::Log4perl with log4j's Chainsaw?
  1125. Yes, Log::Log4perl can be configured to send its events to log4j's
  1126. graphical log UI I<Chainsaw>.
  1127. =for html
  1128. <p>
  1129. <TABLE><TR><TD>
  1130. <A HREF="http://log4perl.sourceforge.net/images/chainsaw2.jpg"><IMG SRC="http://log4perl.sourceforge.net/images/chainsaw2s.jpg"></A>
  1131. <TR><TD>
  1132. <I>Figure 1: Chainsaw receives Log::Log4perl events</I>
  1133. </TABLE>
  1134. <p>
  1135. =for text
  1136. Figure1: Chainsaw receives Log::Log4perl events
  1137. Here's how it works:
  1138. =over 4
  1139. =item *
  1140. Get Guido Carls' E<lt>gcarls@cpan.orgE<gt> Log::Log4perl extension
  1141. C<Log::Log4perl::Layout::XMLLayout> from CPAN and install it:
  1142. perl -MCPAN -eshell
  1143. cpan> install Log::Log4perl::Layout::XMLLayout
  1144. =item *
  1145. Install and start Chainsaw, which is part of the C<log4j> distribution now
  1146. (see http://jakarta.apache.org/log4j ). Create a configuration file like
  1147. <log4j:configuration debug="true">
  1148. <plugin name="XMLSocketReceiver"
  1149. class="org.apache.log4j.net.XMLSocketReceiver">
  1150. <param name="decoder" value="org.apache.log4j.xml.XMLDecoder"/>
  1151. <param name="Port" value="4445"/>
  1152. </plugin>
  1153. <root> <level value="debug"/> </root>
  1154. </log4j:configuration>
  1155. and name it e.g. C<config.xml>. Then start Chainsaw like
  1156. java -Dlog4j.debug=true -Dlog4j.configuration=config.xml \
  1157. -classpath ".:log4j-1.3alpha.jar:log4j-chainsaw-1.3alpha.jar" \
  1158. org.apache.log4j.chainsaw.LogUI
  1159. and watch the GUI coming up.
  1160. =item *
  1161. Configure Log::Log4perl to use a socket appender with an XMLLayout, pointing
  1162. to the host/port where Chainsaw (as configured above) is waiting with its
  1163. XMLSocketReceiver:
  1164. use Log::Log4perl qw(get_logger);
  1165. use Log::Log4perl::Layout::XMLLayout;
  1166. my $conf = q(
  1167. log4perl.category.Bar.Twix = WARN, Appender
  1168. log4perl.appender.Appender = Log::Log4perl::Appender::Socket
  1169. log4perl.appender.Appender.PeerAddr = localhost
  1170. log4perl.appender.Appender.PeerPort = 4445
  1171. log4perl.appender.Appender.layout = Log::Log4perl::Layout::XMLLayout
  1172. );
  1173. Log::Log4perl::init(\$conf);
  1174. # Nasty hack to suppress encoding header
  1175. my $app = Log::Log4perl::appenders->{"Appender"};
  1176. $app->layout()->{enc_set} = 1;
  1177. my $logger = get_logger("Bar.Twix");
  1178. $logger->error("One");
  1179. The nasty hack shown in the code snippet above is currently (October 2003)
  1180. necessary, because Chainsaw expects XML messages to arrive in a format like
  1181. <log4j:event logger="Bar.Twix"
  1182. timestamp="1066794904310"
  1183. level="ERROR"
  1184. thread="10567">
  1185. <log4j:message><![CDATA[Two]]></log4j:message>
  1186. <log4j:NDC><![CDATA[undef]]></log4j:NDC>
  1187. <log4j:locationInfo class="main"
  1188. method="main"
  1189. file="./t"
  1190. line="32">
  1191. </log4j:locationInfo>
  1192. </log4j:event>
  1193. without a preceding
  1194. <?xml version = "1.0" encoding = "iso8859-1"?>
  1195. which Log::Log4perl::Layout::XMLLayout applies to the first event sent
  1196. over the socket.
  1197. =back
  1198. See figure 1 for a screenshot of Chainsaw in action, receiving events from
  1199. the Perl script shown above.
  1200. Many thanks to Chainsaw's
  1201. Scott Deboy <sdeboy@comotivsystems.com> for his support!
  1202. =head2 How can I run Log::Log4perl under mod_perl?
  1203. In persistent environments it's important to play by the rules outlined
  1204. in section L<Log::Log4perl/"Initialize once and only once">.
  1205. If you haven't read this yet, please go ahead and read it right now. It's
  1206. very important.
  1207. And no matter if you use a startup handler to init() Log::Log4perl or use the
  1208. init_once() strategy (added in 0.42), either way you're very likely to have
  1209. unsynchronized writes to logfiles.
  1210. If Log::Log4perl is configured with a log file appender, and it is
  1211. initialized via
  1212. the Apache startup handler, the file handle created initially will be
  1213. shared among all Apache processes. Similarly, with the init_once()
  1214. approach: although every process has a separate L4p configuration,
  1215. processes are gonna share the appender file I<names> instead, effectively
  1216. opening several different file handles on the same file.
  1217. Now, having several appenders using the same file handle or having
  1218. several appenders logging to the same file unsynchronized, this might
  1219. result in overlapping messages. Sometimes, this is acceptable. If it's
  1220. not, here's two strategies:
  1221. =over 4
  1222. =item *
  1223. Use the L<Log::Log4perl::Appender::Synchronized> appender to connect to
  1224. your file appenders. Here's the writeup:
  1225. http://log4perl.sourceforge.net/releases/Log-Log4perl/docs/html/Log/Log4perl/FAQ.html#23804
  1226. =item *
  1227. Use a different logfile for every process like in
  1228. #log4perl.conf
  1229. ...
  1230. log4perl.appender.A1.filename = sub { "mylog.$$.log" }
  1231. =back
  1232. =head2 My program already uses warn() and die(). How can I switch to Log4perl?
  1233. If your program already uses Perl's C<warn()> function to spew out
  1234. error messages and you'd like to channel those into the Log4perl world,
  1235. just define a C<__WARN__> handler where your program or module resides:
  1236. use Log::Log4perl qw(:easy);
  1237. $SIG{__WARN__} = sub {
  1238. local $Log::Log4perl::caller_depth =
  1239. $Log::Log4perl::caller_depth + 1;
  1240. WARN @_;
  1241. };
  1242. Why the C<local> setting of C<$Log::Log4perl::caller_depth>?
  1243. If you leave that out,
  1244. C<PatternLayout> conversion specifiers like C<%M> or C<%F> (printing
  1245. the current function/method and source filename) will refer
  1246. to where the __WARN__ handler resides, not the environment
  1247. Perl's C<warn()> function was issued from. Increasing C<caller_depth>
  1248. adjusts for this offset. Having it C<local>, makes sure the level
  1249. gets set back after the handler exits.
  1250. Once done, if your program does something like
  1251. sub some_func {
  1252. warn "Here's a warning";
  1253. }
  1254. you'll get (depending on your Log::Log4perl configuration) something like
  1255. 2004/02/19 20:41:02-main::some_func: Here's a warning at ./t line 25.
  1256. in the appropriate appender instead of having a screen full of STDERR
  1257. messages. It also works with the C<Carp> module and its C<carp()>
  1258. and C<cluck()> functions.
  1259. If, on the other hand, catching C<die()> and friends is
  1260. required, a C<__DIE__> handler is appropriate:
  1261. $SIG{__DIE__} = sub {
  1262. if($^S) {
  1263. # We're in an eval {} and don't want log
  1264. # this message but catch it later
  1265. return;
  1266. }
  1267. local $Log::Log4perl::caller_depth =
  1268. $Log::Log4perl::caller_depth + 1;
  1269. LOGDIE @_;
  1270. };
  1271. This will call Log4perl's C<LOGDIE()> function, which will log a fatal
  1272. error and then call die() internally, causing the program to exit. Works
  1273. equally well with C<Carp>'s C<croak()> and C<confess()> functions.
  1274. =head2 Some module prints messages to STDERR. How can I funnel them to Log::Log4perl?
  1275. If a module you're using doesn't use Log::Log4perl but prints logging
  1276. messages to STDERR instead, like
  1277. ########################################
  1278. package IgnorantModule;
  1279. ########################################
  1280. sub some_method {
  1281. print STDERR "Parbleu! An error!\n";
  1282. }
  1283. 1;
  1284. there's still a way to capture these messages and funnel them
  1285. into Log::Log4perl, even without touching the module. What you need is
  1286. a trapper module like
  1287. ########################################
  1288. package Trapper;
  1289. ########################################
  1290. use Log::Log4perl qw(:easy);
  1291. sub TIEHANDLE {
  1292. my $class = shift;
  1293. bless [], $class;
  1294. }
  1295. sub PRINT {
  1296. my $self = shift;
  1297. $Log::Log4perl::caller_depth++;
  1298. DEBUG @_;
  1299. $Log::Log4perl::caller_depth--;
  1300. }
  1301. 1;
  1302. and a C<tie> command in the main program to tie STDERR to the trapper
  1303. module along with regular Log::Log4perl initialization:
  1304. ########################################
  1305. package main;
  1306. ########################################
  1307. use Log::Log4perl qw(:easy);
  1308. Log::Log4perl->easy_init(
  1309. {level => $DEBUG,
  1310. file => 'stdout', # make sure not to use stderr here!
  1311. layout => "%d %M: %m%n",
  1312. });
  1313. tie *STDERR, "Trapper";
  1314. Make sure not to use STDERR as Log::Log4perl's file appender
  1315. here (which would be the default in C<:easy> mode), because it would
  1316. end up in an endless recursion.
  1317. Now, calling
  1318. IgnorantModule::some_method();
  1319. will result in the desired output
  1320. 2004/05/06 11:13:04 IgnorantModule::some_method: Parbleu! An error!
  1321. =head2 How come PAR (Perl Archive Toolkit) creates executables which then can't find their Log::Log4perl appenders?
  1322. If not instructed otherwise, C<Log::Log4perl> dynamically pulls in
  1323. appender classes found in its configuration. If you specify
  1324. #!/usr/bin/perl
  1325. # mytest.pl
  1326. use Log::Log4perl qw(get_logger);
  1327. my $conf = q(
  1328. log4perl.category.Bar.Twix = WARN, Logfile
  1329. log4perl.appender.Logfile = Log::Log4perl::Appender::Screen
  1330. log4perl.appender.Logfile.layout = SimpleLayout
  1331. );
  1332. Log::Log4perl::init(\$conf);
  1333. my $logger = get_logger("Bar::Twix");
  1334. $logger->error("Blah");
  1335. then C<Log::Log4perl::Appender::Screen> will be pulled in while the program
  1336. runs, not at compile time. If you have PAR compile the script above to an
  1337. executable binary via
  1338. pp -o mytest mytest.pl
  1339. and then run C<mytest> on a machine without having Log::Log4perl installed,
  1340. you'll get an error message like
  1341. ERROR: can't load appenderclass 'Log::Log4perl::Appender::Screen'
  1342. Can't locate Log/Log4perl/Appender/Screen.pm in @INC ...
  1343. Why? At compile time, C<pp> didn't realize that
  1344. C<Log::Log4perl::Appender::Screen> would be needed later on and didn't
  1345. wrap it into the executable created. To avoid this, either say
  1346. C<use Log::Log4perl::Appender::Screen> in the script explicitly or
  1347. compile it with
  1348. pp -o mytest -M Log::Log4perl::Appender::Screen mytest.pl
  1349. to make sure the appender class gets included.
  1350. =head2 How can I access a custom appender defined in the configuration?
  1351. Any appender defined in the configuration file or somewhere in the code
  1352. can be accessed later via
  1353. C<Log::Log4perl-E<gt>appender_by_name("appender_name")>,
  1354. which returns a reference of the appender object.
  1355. Once you've got a hold of the object, it can be queried or modified to
  1356. your liking. For example, see the custom C<IndentAppender> defined below:
  1357. After calling C<init()> to define the Log4perl settings, the
  1358. appender object is retrieved to call its C<indent_more()> and C<indent_less()>
  1359. methods to control indentation of messages:
  1360. package IndentAppender;
  1361. sub new {
  1362. bless { indent => 0 }, $_[0];
  1363. }
  1364. sub indent_more { $_[0]->{indent}++ }
  1365. sub indent_less { $_[0]->{indent}-- }
  1366. sub log {
  1367. my($self, %params) = @_;
  1368. print " " x $self->{indent}, $params{message};
  1369. }
  1370. package main;
  1371. use Log::Log4perl qw(:easy);
  1372. my $conf = q(
  1373. log4perl.category = DEBUG, Indented
  1374. log4perl.appender.Indented = IndentAppender
  1375. log4perl.appender.Indented.layout = Log::Log4perl::Layout::SimpleLayout
  1376. );
  1377. Log::Log4perl::init(\$conf);
  1378. my $appender = Log::Log4perl->appender_by_name("Indented");
  1379. DEBUG "No identation";
  1380. $appender->indent_more();
  1381. DEBUG "One more";
  1382. $appender->indent_more();
  1383. DEBUG "Two more";
  1384. $appender->indent_less();
  1385. DEBUG "One less";
  1386. As you would expect, this will print
  1387. DEBUG - No identation
  1388. DEBUG - One more
  1389. DEBUG - Two more
  1390. DEBUG - One less
  1391. because the very appender used by Log4perl is modified dynamically at
  1392. runtime.
  1393. =head2 I don't know if Log::Log4perl is installed. How can I prepare my script?
  1394. In case your script needs to be prepared for environments that may or may
  1395. not have Log::Log4perl installed, there's a trick.
  1396. If you put the following BEGIN blocks at the top of the program,
  1397. you'll be able to use the DEBUG(), INFO(), etc. macros in
  1398. Log::Log4perl's C<:easy> mode.
  1399. If Log::Log4perl
  1400. is installed in the target environment, the regular Log::Log4perl rules
  1401. apply. If not, all of DEBUG(), INFO(), etc. are "stubbed" out, i.e. they
  1402. turn into no-ops:
  1403. use warnings;
  1404. use strict;
  1405. BEGIN {
  1406. eval { require Log::Log4perl; };
  1407. if($@) {
  1408. print "Log::Log4perl not installed - stubbing.\n";
  1409. no strict qw(refs);
  1410. *{"main::$_"} = sub { } for qw(DEBUG INFO WARN ERROR FATAL);
  1411. } else {
  1412. no warnings;
  1413. print "Log::Log4perl installed - life is good.\n";
  1414. require Log::Log4perl::Level;
  1415. Log::Log4perl::Level->import(__PACKAGE__);
  1416. Log::Log4perl->import(qw(:easy));
  1417. Log::Log4perl->easy_init($main::DEBUG);
  1418. }
  1419. }
  1420. # The regular script begins ...
  1421. DEBUG "Hey now!";
  1422. This snippet will first probe for Log::Log4perl, and if it can't be found,
  1423. it will alias DEBUG(), INFO(), with empty subroutines via typeglobs.
  1424. If Log::Log4perl is available, its level constants are first imported
  1425. (C<$DEBUG>, C<$INFO>, etc.) and then C<easy_init()> gets called to initialize
  1426. the logging system.
  1427. =head2 Can file appenders create files with different permissions?
  1428. Typically, when C<Log::Log4perl::Appender::File> creates a new file,
  1429. its permissions are set to C<rw-r--r-->. Why? Because your
  1430. environment's I<umask> most likely defaults to
  1431. C<0022>, that's the standard setting.
  1432. What's a I<umask>, you're asking? It's a template that's applied to
  1433. the permissions of all newly created files. While calls like
  1434. C<open(FILE, "E<gt>foo")> will always try to create files in C<rw-rw-rw-
  1435. > mode, the system will apply the current I<umask> template to
  1436. determine the final permission setting. I<umask> is a bit mask that's
  1437. inverted and then applied to the requested permission setting, using a
  1438. bitwise AND:
  1439. $request_permission &~ $umask
  1440. So, a I<umask> setting of 0000 (the leading 0 simply indicates an
  1441. octal value) will create files in C<rw-rw-rw-> mode, a setting of 0277
  1442. will use C<r-------->, and the standard 0022 will use C<rw-r--r-->.
  1443. As an example, if you want your log files to be created with
  1444. C<rw-r--rw-> permissions, use a I<umask> of C<0020> before
  1445. calling Log::Log4perl->init():
  1446. use Log::Log4perl;
  1447. umask 0020;
  1448. # Creates log.out in rw-r--rw mode
  1449. Log::Log4perl->init(\ q{
  1450. log4perl.logger = WARN, File
  1451. log4perl.appender.File = Log::Log4perl::Appender::File
  1452. log4perl.appender.File.filename = log.out
  1453. log4perl.appender.File.layout = SimpleLayout
  1454. });
  1455. =head2 Using Log4perl in an END block causes a problem!
  1456. It's not easy to get to this error, but if you write something like
  1457. END { Log::Log4perl::get_logger()->debug("Hey there."); }
  1458. use Log::Log4perl qw(:easy);
  1459. Log::Log4perl->easy_init($DEBUG);
  1460. it won't work. The reason is that C<Log::Log4perl> defines an
  1461. END block that cleans up all loggers. And perl will run END blocks
  1462. in the reverse order as they're encountered in the compile phase,
  1463. so in the scenario above, the END block will run I<after> Log4perl
  1464. has cleaned up its loggers.
  1465. Placing END blocks using Log4perl I<after>
  1466. a C<use Log::Log4perl> statement fixes the problem:
  1467. use Log::Log4perl qw(:easy);
  1468. Log::Log4perl->easy_init($DEBUG);
  1469. END { Log::Log4perl::get_logger()->debug("Hey there."); }
  1470. In this scenario, the shown END block is executed I<before> Log4perl
  1471. cleans up and the debug message will be processed properly.
  1472. =head2 Help! My appender is throwing a "Wide character in print" warning!
  1473. This warning shows up when Unicode strings are printed without
  1474. precautions. The warning goes away if the complaining appender is
  1475. set to utf-8 mode:
  1476. # Either in the log4perl configuration file:
  1477. log4perl.appender.Logfile.filename = test.log
  1478. log4perl.appender.Logfile.utf8 = 1
  1479. # Or, in easy mode:
  1480. Log::Log4perl->easy_init( {
  1481. level => $DEBUG,
  1482. file => ":utf8> test.log"
  1483. } );
  1484. If the complaining appender is a screen appender, set its C<utf8> option:
  1485. log4perl.appender.Screen.stderr = 1
  1486. log4perl.appender.Screen.utf8 = 1
  1487. Alternatively, C<binmode> does the trick:
  1488. # Either STDOUT ...
  1489. binmode(STDOUT, ":utf8);
  1490. # ... or STDERR.
  1491. binmode(STDERR, ":utf8);
  1492. Some background on this: Perl's strings are either byte strings or
  1493. Unicode strings. C<"Mike"> is a byte string.
  1494. C<"\x{30DE}\x{30A4}\x{30AF}"> is a Unicode string. Unicode strings are
  1495. marked specially and are UTF-8 encoded internally.
  1496. If you print a byte string to STDOUT,
  1497. all is well, because STDOUT is by default set to byte mode. However,
  1498. if you print a Unicode string to STDOUT without precautions, C<perl>
  1499. will try to transform the Unicode string back to a byte string before
  1500. printing it out. This is troublesome if the Unicode string contains
  1501. 'wide' characters which can't be represented in Latin-1.
  1502. For example, if you create a Unicode string with three japanese Katakana
  1503. characters as in
  1504. perl -le 'print "\x{30DE}\x{30A4}\x{30AF}"'
  1505. (coincidentally pronounced Ma-i-ku, the japanese pronunciation of
  1506. "Mike"), STDOUT is in byte mode and the warning
  1507. Wide character in print at ./script.pl line 14.
  1508. appears. Setting STDOUT to UTF-8 mode as in
  1509. perl -le 'binmode(STDOUT, ":utf8"); print "\x{30DE}\x{30A4}\x{30AF}"'
  1510. will silently print the Unicode string to STDOUT in UTF-8. To see the
  1511. characters printed, you'll need a UTF-8 terminal with a font including
  1512. japanese Katakana characters.
  1513. =head2 How can I send errors to the screen, and debug messages to a file?
  1514. Let's assume you want to maintain a detailed DEBUG output in a file
  1515. and only messages of level ERROR and higher should be printed on the
  1516. screen. Often times, developers come up with something like this:
  1517. # Wrong!!!
  1518. log4perl.logger = DEBUG, FileApp
  1519. log4perl.logger = ERROR, ScreenApp
  1520. # Wrong!!!
  1521. This won't work, however. Logger definitions aren't additive, and the
  1522. second statement will overwrite the first one. Log4perl versions
  1523. below 1.04 were silently accepting this, leaving people confused why
  1524. it wouldn't work as expected.
  1525. As of 1.04, this will throw a I<fatal error> to notify the user of
  1526. the problem.
  1527. What you want to do instead, is this:
  1528. log4perl.logger = DEBUG, FileApp, ScreenApp
  1529. log4perl.appender.FileApp = Log::Log4perl::Appender::File
  1530. log4perl.appender.FileApp.filename = test.log
  1531. log4perl.appender.FileApp.layout = SimpleLayout
  1532. log4perl.appender.ScreenApp = Log::Log4perl::Appender::Screen
  1533. log4perl.appender.ScreenApp.stderr = 0
  1534. log4perl.appender.ScreenApp.layout = SimpleLayout
  1535. ### limiting output to ERROR messages
  1536. log4perl.appender.ScreenApp.Threshold = ERROR
  1537. ###
  1538. Note that without the second appender's C<Threshold> setting, both appenders
  1539. would receive all messages prioritized DEBUG and higher. With the
  1540. threshold set to ERROR, the second appender will filter the messages
  1541. as required.
  1542. =head2 Where should I put my logfiles?
  1543. Your log files may go anywhere you want them, but the effective
  1544. user id of the calling process must have write access.
  1545. If the log file doesn't exist at program start, Log4perl's file appender
  1546. will create it. For this, it needs write access to the directory where
  1547. the new file will be located in. If the log file already exists at startup,
  1548. the process simply needs write access to the file. Note that it will
  1549. need write access to the file's directory if you're encountering situations
  1550. where the logfile gets recreated, e.g. during log rotation.
  1551. If Log::Log4perl is used by a web server application (e.g. in a CGI script
  1552. or mod_perl), then the webserver's user (usually C<nobody> or C<www>)
  1553. must have the permissions mentioned above.
  1554. To prepare your web server to use log4perl, we'd recommend:
  1555. webserver:~$ su -
  1556. webserver:~# mkdir /var/log/cgiapps
  1557. webserver:~# chown nobody:root /var/log/cgiapps/
  1558. webserver:~# chown nobody:root -R /var/log/cgiapps/
  1559. webserver:~# chmod 02755 -R /var/log/cgiapps/
  1560. Then set your /etc/log4perl.conf file to include:
  1561. log4perl.appender.FileAppndr1.filename =
  1562. /var/log/cgiapps/<app-name>.log
  1563. =head2 How can my file appender deal with disappearing log files?
  1564. The file appender that comes with Log4perl, L<Log::Log4perl::Appender::File>,
  1565. will open a specified log file at initialization time and will
  1566. keep writing to it via a file handle.
  1567. In case the associated file goes way, messages written by a
  1568. long-running process will still be written
  1569. to the file handle. In case the file has been moved to a different
  1570. location on the same file system, the writer will keep writing to
  1571. it under the new filename. In case the file has been removed from
  1572. the file system, the log messages will end up in nowhere land. This
  1573. is not a bug in Log4perl, this is how Unix works. There is
  1574. no error message in this case, because the writer has no idea that
  1575. the file handle is not associated with a visible file.
  1576. To prevent the loss of log messages when log files disappear, the
  1577. file appender's C<recreate> option needs to be set to a true value:
  1578. log4perl.appender.Logfile.recreate = 1
  1579. This will instruct the file appender to check in regular intervals
  1580. (default: 30 seconds) if the log file is still there. If it finds
  1581. out that the file is missing, it will recreate it.
  1582. Continuously checking if the log file still exists is fairly
  1583. expensive. For this reason it is only performed every 30 seconds. To
  1584. change this interval, the option C<recreate_check_interval> can be set
  1585. to the number of seconds between checks. In the extreme case where the
  1586. check should be performed before every write, it can even be set to 0:
  1587. log4perl.appender.Logfile.recreate = 1
  1588. log4perl.appender.Logfile.recreate_check_interval = 0
  1589. To avoid having to check the file system so frequently, a signal
  1590. handler can be set up:
  1591. log4perl.appender.Logfile.recreate = 1
  1592. log4perl.appender.Logfile.recreate_check_signal = USR1
  1593. This will install a signal handler which will recreate a missing log file
  1594. immediately when it receives the defined signal.
  1595. Note that the init_and_watch() method for Log4perl's initialization
  1596. can also be instructed to install a signal handler, usually using the
  1597. HUP signal. Make sure to use a different signal if you're using both
  1598. of them at the same time.
  1599. =head2 How can I rotate a logfile with newsyslog?
  1600. Here's a few things that need to be taken care of when using the popular
  1601. log file rotating utility C<newsyslog>
  1602. (http://www.courtesan.com/newsyslog) with Log4perl's file appender
  1603. in long-running processes.
  1604. For example, with a newsyslog configuration like
  1605. # newsyslog.conf
  1606. /tmp/test.log 666 12 5 * B
  1607. and a call to
  1608. # newsyslog -f /path/to/newsyslog.conf
  1609. C<newsyslog> will take action if C</tmp/test.log> is larger than the
  1610. specified 5K in size. It will move the current log file C</tmp/test.log> to
  1611. C</tmp/test.log.0> and create a new and empty C</tmp/test.log> with
  1612. the specified permissions (this is why C<newsyslog> needs to run as root).
  1613. An already existing C</tmp/test.log.0> would be moved to
  1614. C</tmp/test.log.1>, C</tmp/test.log.1> to C</tmp/test.log.2>, and so
  1615. forth, for every one of a max number of 12 archived logfiles that have
  1616. been configured in C<newsyslog.conf>.
  1617. Although a new file has been created, from Log4perl's appender's point
  1618. of view, this situation is identical to the one described in the
  1619. previous FAQ entry, labeled C<How can my file appender deal with
  1620. disappearing log files>.
  1621. To make sure that log messages are written to the new log file and not
  1622. to an archived one or end up in nowhere land,
  1623. the appender's C<recreate> and C<recreate_check_interval> have to be
  1624. configured to deal with the 'disappearing' log file.
  1625. The situation gets interesting when C<newsyslog>'s option
  1626. to compress archived log files is enabled. This causes the
  1627. original log file not to be moved, but to disappear. If the
  1628. file appender isn't configured to recreate the logfile in this situation,
  1629. log messages will actually be lost without warning. This also
  1630. applies for the short time frame of C<recreate_check_interval> seconds
  1631. in between the recreator's file checks.
  1632. To make sure that no messages get lost, one option is to set the
  1633. interval to
  1634. log4perl.appender.Logfile.recreate_check_interval = 0
  1635. However, this is fairly expensive. A better approach is to define
  1636. a signal handler:
  1637. log4perl.appender.Logfile.recreate = 1
  1638. log4perl.appender.Logfile.recreate_check_signal = USR1
  1639. log4perl.appender.Logfile.recreate_pid_write = /tmp/myappid
  1640. As a service for C<newsyslog> users, Log4perl's file appender writes
  1641. the current process ID to a PID file specified by the C<recreate_pid_write>
  1642. option. C<newsyslog> then needs to be configured as in
  1643. # newsyslog.conf configuration for compressing archive files and
  1644. # sending a signal to the Log4perl-enabled application
  1645. /tmp/test.log 666 12 5 * B /tmp/myappid 30
  1646. to send the defined signal (30, which is USR1 on FreeBSD) to the
  1647. application process at rotation time. Note that the signal number
  1648. is different on Linux, where USR1 denotes as 10. Check C<man signal>
  1649. for details.
  1650. =head2 How can a process under user id A log to a file under user id B?
  1651. This scenario often occurs in configurations where processes run under
  1652. various user IDs but need to write to a log file under a fixed, but
  1653. different user id.
  1654. With a traditional file appender, the log file will probably be created
  1655. under one user's id and appended to under a different user's id. With
  1656. a typical umask of 0002, the file will be created with -rw-rw-r--
  1657. permissions. If a user who's not in the first user's group
  1658. subsequently appends to the log file, it will fail because of a
  1659. permission problem.
  1660. Two potential solutions come to mind:
  1661. =over 4
  1662. =item *
  1663. Creating the file with a umask of 0000 will allow all users to append
  1664. to the log file. Log4perl's file appender C<Log::Log4perl::Appender::File>
  1665. has an C<umask> option that can be set to support this:
  1666. log4perl.appender.File = Log::Log4perl::Appender::File
  1667. log4perl.appender.File.umask = sub { 0000 };
  1668. This way, the log file will be created with -rw-rw-rw- permissions and
  1669. therefore has world write permissions. This might open up the logfile
  1670. for unwanted manipulations by arbitrary users, though.
  1671. =item *
  1672. Running the process under an effective user id of C<root> will allow
  1673. it to write to the log file, no matter who started the process.
  1674. However, this is not a good idea, because of security concerns.
  1675. =back
  1676. Luckily, under Unix, there's the syslog daemon which runs as root and
  1677. takes log requests from user processes over a socket and writes them
  1678. to log files as configured in C</etc/syslog.conf>.
  1679. By modifying C</etc/syslog.conf> and HUPing the syslog daemon, you can
  1680. configure new log files:
  1681. # /etc/syslog.conf
  1682. ...
  1683. user.* /some/path/file.log
  1684. Using the C<Log::Dispatch::Syslog> appender, which comes with the
  1685. C<Log::Log4perl> distribution, you can then send messages via syslog:
  1686. use Log::Log4perl qw(:easy);
  1687. Log::Log4perl->init(\<<EOT);
  1688. log4perl.logger = DEBUG, app
  1689. log4perl.appender.app=Log::Dispatch::Syslog
  1690. log4perl.appender.app.Facility=user
  1691. log4perl.appender.app.layout=SimpleLayout
  1692. EOT
  1693. # Writes to /some/path/file.log
  1694. ERROR "Message!";
  1695. This way, the syslog daemon will solve the permission problem.
  1696. Note that while it is possible to use syslog() without Log4perl (syslog
  1697. supports log levels, too), traditional syslog setups have a
  1698. significant drawback.
  1699. Without Log4perl's ability to activate logging in only specific
  1700. parts of a system, complex systems will trigger log events all over
  1701. the place and slow down execution to a crawl at high debug levels.
  1702. Remote-controlling logging in the hierarchical parts of an application
  1703. via Log4perl's categories is one of its most distinguished features.
  1704. It allows for enabling high debug levels in specified areas without
  1705. noticeable performance impact.
  1706. =head2 I want to use UTC instead of the local time!
  1707. If a layout defines a date, Log::Log4perl uses local time to populate it.
  1708. If you want UTC instead, set
  1709. log4perl.utcDateTimes = 1
  1710. in your configuration. Alternatively, you can set
  1711. $Log::Log4perl::DateFormat::GMTIME = 1;
  1712. in your program before the first log statement.
  1713. =head2 Can Log4perl intercept messages written to a filehandle?
  1714. You have a function that prints to a filehandle. You want to tie
  1715. into that filehandle and forward all arriving messages to a
  1716. Log4perl logger.
  1717. First, let's write a package that ties a file handle and forwards it
  1718. to a Log4perl logger:
  1719. package FileHandleLogger;
  1720. use Log::Log4perl qw(:levels get_logger);
  1721. sub TIEHANDLE {
  1722. my($class, %options) = @_;
  1723. my $self = {
  1724. level => $DEBUG,
  1725. category => '',
  1726. %options
  1727. };
  1728. $self->{logger} = get_logger($self->{category}),
  1729. bless $self, $class;
  1730. }
  1731. sub PRINT {
  1732. my($self, @rest) = @_;
  1733. $Log::Log4perl::caller_depth++;
  1734. $self->{logger}->log($self->{level}, @rest);
  1735. $Log::Log4perl::caller_depth--;
  1736. }
  1737. sub PRINTF {
  1738. my($self, $fmt, @rest) = @_;
  1739. $Log::Log4perl::caller_depth++;
  1740. $self->PRINT(sprintf($fmt, @rest));
  1741. $Log::Log4perl::caller_depth--;
  1742. }
  1743. 1;
  1744. Now, if you have a function like
  1745. sub function_printing_to_fh {
  1746. my($fh) = @_;
  1747. printf $fh "Hi there!\n";
  1748. }
  1749. which takes a filehandle and prints something to it, it can be used
  1750. with Log4perl:
  1751. use Log::Log4perl qw(:easy);
  1752. usa FileHandleLogger;
  1753. Log::Log4perl->easy_init($DEBUG);
  1754. tie *SOMEHANDLE, 'FileHandleLogger' or
  1755. die "tie failed ($!)";
  1756. function_printing_to_fh(*SOMEHANDLE);
  1757. # prints "2007/03/22 21:43:30 Hi there!"
  1758. If you want, you can even specify a different log level or category:
  1759. tie *SOMEHANDLE, 'FileHandleLogger',
  1760. level => $INFO, category => "Foo::Bar" or die "tie failed ($!)";
  1761. =head2 I want multiline messages rendered line-by-line!
  1762. With the standard C<PatternLayout>, if you send a multiline message to
  1763. an appender as in
  1764. use Log::Log4perl qw(:easy);
  1765. Log
  1766. it gets rendered this way:
  1767. 2007/04/04 23:23:39 multi
  1768. line
  1769. message
  1770. If you want each line to be rendered separately according to
  1771. the layout use C<Log::Log4perl::Layout::PatternLayout::Multiline>:
  1772. use Log::Log4perl qw(:easy);
  1773. Log::Log4perl->init(\<<EOT);
  1774. log4perl.category = DEBUG, Screen
  1775. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  1776. log4perl.appender.Screen.layout = \\
  1777. Log::Log4perl::Layout::PatternLayout::Multiline
  1778. log4perl.appender.Screen.layout.ConversionPattern = %d %m %n
  1779. EOT
  1780. DEBUG "some\nmultiline\nmessage";
  1781. and you'll get
  1782. 2007/04/04 23:23:39 some
  1783. 2007/04/04 23:23:39 multiline
  1784. 2007/04/04 23:23:39 message
  1785. instead.
  1786. =head2 I'm on Windows and I'm getting all these 'redefined' messages!
  1787. If you're on Windows and are getting warning messages like
  1788. Constant subroutine Log::Log4perl::_INTERNAL_DEBUG redefined at
  1789. C:/Programme/Perl/lib/constant.pm line 103.
  1790. Subroutine import redefined at
  1791. C:/Programme/Perl/site/lib/Log/Log4Perl.pm line 69.
  1792. Subroutine initialized redefined at
  1793. C:/Programme/Perl/site/lib/Log/Log4Perl.pm line 207.
  1794. then chances are that you're using 'Log::Log4Perl' (wrong uppercase P)
  1795. instead of the correct 'Log::Log4perl'. Perl on Windows doesn't
  1796. handle this error well and spits out a slew of confusing warning
  1797. messages. But now you know, just use the correct module name and
  1798. you'll be fine.
  1799. =head2 Log4perl complains that no initialization happened during shutdown!
  1800. If you're using Log4perl log commands in DESTROY methods of your objects,
  1801. you might see confusing messages like
  1802. Log4perl: Seems like no initialization happened. Forgot to call init()?
  1803. Use of uninitialized value in subroutine entry at
  1804. /home/y/lib/perl5/site_perl/5.6.1/Log/Log4perl.pm line 134 during global
  1805. destruction. (in cleanup) Undefined subroutine &main:: called at
  1806. /home/y/lib/perl5/site_perl/5.6.1/Log/Log4perl.pm line 134 during global
  1807. destruction.
  1808. when the program shuts down. What's going on?
  1809. This phenomenon happens if you have circular references in your objects,
  1810. which perl can't clean up when an object goes out of scope but waits
  1811. until global destruction instead. At this time, however, Log4perl has
  1812. already shut down, so you can't use it anymore.
  1813. For example, here's a simple class which uses a logger in its DESTROY
  1814. method:
  1815. package A;
  1816. use Log::Log4perl qw(:easy);
  1817. sub new { bless {}, shift }
  1818. sub DESTROY { DEBUG "Waaah!"; }
  1819. Now, if the main program creates a self-referencing object, like in
  1820. package main;
  1821. use Log::Log4perl qw(:easy);
  1822. Log::Log4perl->easy_init($DEBUG);
  1823. my $a = A->new();
  1824. $a->{selfref} = $a;
  1825. then you'll see the error message shown above during global destruction.
  1826. How to tackle this problem?
  1827. First, you should clean up your circular references before global
  1828. destruction. They will not only cause objects to be destroyed in an order
  1829. that's hard to predict, but also eat up memory until the program shuts
  1830. down.
  1831. So, the program above could easily be fixed by putting
  1832. $a->{selfref} = undef;
  1833. at the end or in an END handler. If that's hard to do, use weak references:
  1834. package main;
  1835. use Scalar::Util qw(weaken);
  1836. use Log::Log4perl qw(:easy);
  1837. Log::Log4perl->easy_init($DEBUG);
  1838. my $a = A->new();
  1839. $a->{selfref} = weaken $a;
  1840. This allows perl to clean up the circular reference when the object
  1841. goes out of scope, and doesn't wait until global destruction.
  1842. =head2 How can I access POE heap values from Log4perl's layout?
  1843. POE is a framework for creating multitasked applications running in a
  1844. single process and a single thread. POE's threads equivalents are
  1845. 'sessions' and since they run quasi-simultaneously, you can't use
  1846. Log4perl's global NDC/MDC to hold session-specific data.
  1847. However, POE already maintains a data store for every session. It is called
  1848. 'heap' and is just a hash storing session-specific data in key-value pairs.
  1849. To access this per-session heap data from a Log4perl layout, define a
  1850. custom cspec and reference it with the newly defined pattern in the layout:
  1851. use strict;
  1852. use POE;
  1853. use Log::Log4perl qw(:easy);
  1854. Log::Log4perl->init( \ q{
  1855. log4perl.logger = DEBUG, Screen
  1856. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  1857. log4perl.appender.Screen.layout = PatternLayout
  1858. log4perl.appender.Screen.layout.ConversionPattern = %U %m%n
  1859. log4perl.PatternLayout.cspec.U = \
  1860. sub { POE::Kernel->get_active_session->get_heap()->{ user } }
  1861. } );
  1862. for (qw( Huey Lewey Dewey )) {
  1863. POE::Session->create(
  1864. inline_states => {
  1865. _start => sub {
  1866. $_[HEAP]->{user} = $_;
  1867. POE::Kernel->yield('hello');
  1868. },
  1869. hello => sub {
  1870. DEBUG "I'm here now";
  1871. }
  1872. }
  1873. );
  1874. }
  1875. POE::Kernel->run();
  1876. exit;
  1877. The code snippet above defines a new layout placeholder (called
  1878. 'cspec' in Log4perl) %U which calls a subroutine, retrieves the active
  1879. session, gets its heap and looks up the entry specified ('user').
  1880. Starting with Log::Log4perl 1.20, cspecs also support parameters in
  1881. curly braces, so you can say
  1882. log4perl.appender.Screen.layout.ConversionPattern = %U{user} %U{id} %m%n
  1883. log4perl.PatternLayout.cspec.U = \
  1884. sub { POE::Kernel->get_active_session-> \
  1885. get_heap()->{ $_[0]->{curlies} } }
  1886. and print the POE session heap entries 'user' and 'id' with every logged
  1887. message. For more details on cpecs, read the PatternLayout manual.
  1888. =head2 I want to print something unconditionally!
  1889. Sometimes it's a script that's supposed to log messages regardless if
  1890. Log4perl has been initialized or not. Or there's a logging statement that's
  1891. not going to be suppressed under any circumstances -- many people want to
  1892. have the final word, make the executive decision, because it seems like
  1893. the only logical choice.
  1894. But think about it:
  1895. First off, if a messages is supposed to be printed, where is it supposed
  1896. to end up at? STDOUT? STDERR? And are you sure you want to set in stone
  1897. that this message needs to be printed, while someone else might
  1898. find it annoying and wants to get rid of it?
  1899. The truth is, there's always going to be someone who wants to log a
  1900. messages at all cost, but also another person who wants to suppress it
  1901. with equal vigilance. There's no good way to serve these two conflicting
  1902. desires, someone will always want to win at the cost of leaving
  1903. the other party disappointed.
  1904. So, the best Log4perl offers is the ALWAYS level for a message that even
  1905. fires if the system log level is set to $OFF:
  1906. use Log::Log4perl qw(:easy);
  1907. Log::Log4perl->easy_init( $OFF );
  1908. ALWAYS "This gets logged always. Well, almost always";
  1909. The logger won't fire, though, if Log4perl hasn't been initialized or
  1910. if someone defines a custom log hurdle that's higher than $OFF.
  1911. Bottom line: Leave the setting of the logging level to the initial Perl
  1912. script -- let their owners decided what they want, no matter how tempting
  1913. it may be to decide it for them.
  1914. =head2 Why doesn't my END handler remove my log file on Win32?
  1915. If you have code like
  1916. use Log::Log4perl qw( :easy );
  1917. Log::Log4perl->easy_init( { level => $DEBUG, file => "my.log" } );
  1918. END { unlink "my.log" or die };
  1919. then you might be in for a surprise when you're running it on
  1920. Windows, because the C<unlink()> call in the END handler will complain that
  1921. the file is still in use.
  1922. What happens in Perl if you have something like
  1923. END { print "first end in main\n"; }
  1924. use Module;
  1925. END { print "second end in main\n"; }
  1926. and
  1927. package Module;
  1928. END { print "end in module\n"; }
  1929. 1;
  1930. is that you get
  1931. second end in main
  1932. end in module
  1933. first end in main
  1934. because perl stacks the END handlers in reverse order in which it
  1935. encounters them in the compile phase.
  1936. Log4perl defines an END handler that cleans up left-over appenders (e.g.
  1937. file appenders which still hold files open), because those appenders have
  1938. circular references and therefore aren't cleaned up otherwise.
  1939. Now if you define an END handler after "use Log::Log4perl", it'll
  1940. trigger before Log4perl gets a chance to clean up, which isn't a
  1941. problem on Unix where you can delete a file even if some process has a
  1942. handle to it open, but it's a problem on Win32, where the OS won't
  1943. let you do that.
  1944. The solution is easy, just place the END handler I<before> Log4perl
  1945. gets loaded, like in
  1946. END { unlink "my.log" or die };
  1947. use Log::Log4perl qw( :easy );
  1948. Log::Log4perl->easy_init( { level => $DEBUG, file => "my.log" } );
  1949. which will call the END handlers in the intended order.
  1950. =cut
  1951. =head1 SEE ALSO
  1952. Log::Log4perl
  1953. =head1 LICENSE
  1954. Copyright 2002-2013 by Mike Schilli E<lt>m@perlmeister.comE<gt>
  1955. and Kevin Goess E<lt>cpan@goess.orgE<gt>.
  1956. This library is free software; you can redistribute it and/or modify
  1957. it under the same terms as Perl itself.
  1958. =head1 AUTHOR
  1959. Please contribute patches to the project on Github:
  1960. http://github.com/mschilli/log4perl
  1961. Send bug reports or requests for enhancements to the authors via our
  1962. MAILING LIST (questions, bug reports, suggestions/patches):
  1963. log4perl-devel@lists.sourceforge.net
  1964. Authors (please contact them via the list above, not directly):
  1965. Mike Schilli <m@perlmeister.com>,
  1966. Kevin Goess <cpan@goess.org>
  1967. Contributors (in alphabetical order):
  1968. Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
  1969. Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
  1970. Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
  1971. Grundman, Paul Harrington, Alexander Hartmaier David Hull,
  1972. Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
  1973. Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope,
  1974. Lars Thegler, David Viner, Mac Yang.