PageRenderTime 38ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Log/Log4perl.pm

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