PageRenderTime 55ms CodeModel.GetById 9ms 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

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

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