PageRenderTime 40ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full 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. # *** R

Large files files are truncated, but you can click here to view the full file