PageRenderTime 63ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Log/Log4perl/Config.pm

http://github.com/mschilli/log4perl
Perl | 1219 lines | 940 code | 155 blank | 124 comment | 74 complexity | a8ebd55b4c3cddd539e1c20f206c4f21 MD5 | raw file
  1. ##################################################
  2. package Log::Log4perl::Config;
  3. ##################################################
  4. use 5.006;
  5. use strict;
  6. use warnings;
  7. use Log::Log4perl::Logger;
  8. use Log::Log4perl::Level;
  9. use Log::Log4perl::Config::PropertyConfigurator;
  10. use Log::Log4perl::JavaMap;
  11. use Log::Log4perl::Filter;
  12. use Log::Log4perl::Filter::Boolean;
  13. use Log::Log4perl::Config::Watch;
  14. use constant _INTERNAL_DEBUG => 0;
  15. our $CONFIG_FILE_READS = 0;
  16. our $CONFIG_INTEGRITY_CHECK = 1;
  17. our $CONFIG_INTEGRITY_ERROR = undef;
  18. our $WATCHER;
  19. our $DEFAULT_WATCH_DELAY = 60; # seconds
  20. our $OPTS = {};
  21. our $OLD_CONFIG;
  22. our $LOGGERS_DEFINED;
  23. our $UTF8 = 0;
  24. ###########################################
  25. sub init {
  26. ###########################################
  27. Log::Log4perl::Logger->reset();
  28. undef $WATCHER; # just in case there's a one left over (e.g. test cases)
  29. return _init(@_);
  30. }
  31. ###########################################
  32. sub utf8 {
  33. ###########################################
  34. my( $class, $flag ) = @_;
  35. $UTF8 = $flag if defined $flag;
  36. return $UTF8;
  37. }
  38. ###########################################
  39. sub watcher {
  40. ###########################################
  41. return $WATCHER;
  42. }
  43. ###########################################
  44. sub init_and_watch {
  45. ###########################################
  46. my ($class, $config, $delay, $opts) = @_;
  47. # delay can be a signal name - in this case we're gonna
  48. # set up a signal handler.
  49. if(defined $WATCHER) {
  50. $config = $WATCHER->file();
  51. if(defined $Log::Log4perl::Config::Watch::SIGNAL_CAUGHT) {
  52. $delay = $WATCHER->signal();
  53. } else {
  54. $delay = $WATCHER->check_interval();
  55. }
  56. }
  57. print "init_and_watch ($config-$delay). Resetting.\n" if _INTERNAL_DEBUG;
  58. Log::Log4perl::Logger->reset();
  59. defined ($delay) or $delay = $DEFAULT_WATCH_DELAY;
  60. if (ref $config) {
  61. die "Log4perl can only watch a file, not a string of " .
  62. "configuration information";
  63. }elsif ($config =~ m!^(https?|ftp|wais|gopher|file):!){
  64. die "Log4perl can only watch a file, not a url like $config";
  65. }
  66. if($delay =~ /\D/) {
  67. $WATCHER = Log::Log4perl::Config::Watch->new(
  68. file => $config,
  69. signal => $delay,
  70. l4p_internal => 1,
  71. );
  72. } else {
  73. $WATCHER = Log::Log4perl::Config::Watch->new(
  74. file => $config,
  75. check_interval => $delay,
  76. l4p_internal => 1,
  77. );
  78. }
  79. if(defined $opts) {
  80. die "Parameter $opts needs to be a hash ref" if ref($opts) ne "HASH";
  81. $OPTS = $opts;
  82. }
  83. eval { _init($class, $config); };
  84. if($@) {
  85. die "$@" unless defined $OLD_CONFIG;
  86. # Call _init with a pre-parsed config to go back to old setting
  87. _init($class, undef, $OLD_CONFIG);
  88. warn "Loading new config failed, reverted to old one\n";
  89. }
  90. }
  91. ##################################################
  92. sub _init {
  93. ##################################################
  94. my($class, $config, $data) = @_;
  95. my %additivity = ();
  96. $LOGGERS_DEFINED = 0;
  97. print "Calling _init\n" if _INTERNAL_DEBUG;
  98. #keep track so we don't create the same one twice
  99. my %appenders_created = ();
  100. #some appenders need to run certain subroutines right at the
  101. #end of the configuration phase, when all settings are in place.
  102. my @post_config_subs = ();
  103. # This logic is probably suited to win an obfuscated programming
  104. # contest. It desperately needs to be rewritten.
  105. # Basically, it works like this:
  106. # config_read() reads the entire config file into a hash of hashes:
  107. # log4j.logger.foo.bar.baz: WARN, A1
  108. # gets transformed into
  109. # $data->{log4j}->{logger}->{foo}->{bar}->{baz} = "WARN, A1";
  110. # The code below creates the necessary loggers, sets the appenders
  111. # and the layouts etc.
  112. # In order to transform parts of this tree back into identifiers
  113. # (like "foo.bar.baz"), we're using the leaf_paths functions below.
  114. # Pretty scary. But it allows the lines of the config file to be
  115. # in *arbitrary* order.
  116. $data = config_read($config) unless defined $data;
  117. if(_INTERNAL_DEBUG) {
  118. require Data::Dumper;
  119. Data::Dumper->import();
  120. print Data::Dumper::Dumper($data);
  121. }
  122. my @loggers = ();
  123. my %filter_names = ();
  124. my $system_wide_threshold;
  125. # Autocorrect the rootlogger/rootLogger typo
  126. if(exists $data->{rootlogger} and
  127. ! exists $data->{rootLogger}) {
  128. $data->{rootLogger} = $data->{rootlogger};
  129. }
  130. # Find all logger definitions in the conf file. Start
  131. # with root loggers.
  132. if(exists $data->{rootLogger}) {
  133. $LOGGERS_DEFINED++;
  134. push @loggers, ["", $data->{rootLogger}->{value}];
  135. }
  136. # Check if we've got a system-wide threshold setting
  137. if(exists $data->{threshold}) {
  138. # yes, we do.
  139. $system_wide_threshold = $data->{threshold}->{value};
  140. }
  141. if (exists $data->{oneMessagePerAppender}){
  142. $Log::Log4perl::one_message_per_appender =
  143. $data->{oneMessagePerAppender}->{value};
  144. }
  145. if(exists $data->{utcDateTimes}) {
  146. require Log::Log4perl::DateFormat;
  147. # Need to split this up in two lines, or CVS will
  148. # mess it up.
  149. $Log::Log4perl::DateFormat::GMTIME =
  150. !!$data->{utcDateTimes}->{value};
  151. }
  152. # Boolean filters
  153. my %boolean_filters = ();
  154. # Continue with lower level loggers. Both 'logger' and 'category'
  155. # are valid keywords. Also 'additivity' is one, having a logger
  156. # attached. We'll differentiate between the two further down.
  157. for my $key (qw(logger category additivity PatternLayout filter)) {
  158. if(exists $data->{$key}) {
  159. for my $path (@{leaf_paths($data->{$key})}) {
  160. print "Path before: @$path\n" if _INTERNAL_DEBUG;
  161. my $value = boolean_to_perlish(pop @$path);
  162. pop @$path; # Drop the 'value' keyword part
  163. if($key eq "additivity") {
  164. # This isn't a logger but an additivity setting.
  165. # Save it in a hash under the logger's name for later.
  166. $additivity{join('.', @$path)} = $value;
  167. #a global user-defined conversion specifier (cspec)
  168. }elsif ($key eq "PatternLayout"){
  169. &add_global_cspec(@$path[-1], $value);
  170. }elsif ($key eq "filter"){
  171. print "Found entry @$path\n" if _INTERNAL_DEBUG;
  172. $filter_names{@$path[0]}++;
  173. } else {
  174. if (ref($value) eq "ARRAY") {
  175. die "Multiple definitions of logger ".join('.',@$path)." in log4perl config";
  176. }
  177. # This is a regular logger
  178. $LOGGERS_DEFINED++;
  179. push @loggers, [join('.', @$path), $value];
  180. }
  181. }
  182. }
  183. }
  184. # Now go over all filters found by name
  185. for my $filter_name (sort keys %filter_names) {
  186. print "Checking filter $filter_name\n" if _INTERNAL_DEBUG;
  187. # The boolean filter needs all other filters already
  188. # initialized, defer its initialization
  189. if($data->{filter}->{$filter_name}->{value} eq
  190. "Log::Log4perl::Filter::Boolean") {
  191. print "Boolean filter ($filter_name)\n" if _INTERNAL_DEBUG;
  192. $boolean_filters{$filter_name}++;
  193. next;
  194. }
  195. my $type = $data->{filter}->{$filter_name}->{value};
  196. if(my $code = compile_if_perl($type)) {
  197. $type = $code;
  198. }
  199. print "Filter $filter_name is of type $type\n" if _INTERNAL_DEBUG;
  200. my $filter;
  201. if(ref($type) eq "CODE") {
  202. # Subroutine - map into generic Log::Log4perl::Filter class
  203. $filter = Log::Log4perl::Filter->new($filter_name, $type);
  204. } else {
  205. # Filter class
  206. die "Filter class '$type' doesn't exist" unless
  207. Log::Log4perl::Util::module_available($type);
  208. eval "require $type" or die "Require of $type failed ($!)";
  209. # Invoke with all defined parameter
  210. # key/values (except the key 'value' which is the entry
  211. # for the class)
  212. $filter = $type->new(name => $filter_name,
  213. map { $_ => $data->{filter}->{$filter_name}->{$_}->{value} }
  214. grep { $_ ne "value" }
  215. sort keys %{$data->{filter}->{$filter_name}});
  216. }
  217. # Register filter with the global filter registry
  218. $filter->register();
  219. }
  220. # Initialize boolean filters (they need the other filters to be
  221. # initialized to be able to compile their logic)
  222. for my $name (sort keys %boolean_filters) {
  223. my $logic = $data->{filter}->{$name}->{logic}->{value};
  224. die "No logic defined for boolean filter $name" unless defined $logic;
  225. my $filter = Log::Log4perl::Filter::Boolean->new(
  226. name => $name,
  227. logic => $logic);
  228. $filter->register();
  229. }
  230. for (@loggers) {
  231. my($name, $value) = @$_;
  232. my $logger = Log::Log4perl::Logger->get_logger($name);
  233. my ($level, @appnames) = split /\s*,\s*/, $value;
  234. $logger->level(
  235. Log::Log4perl::Level::to_priority($level),
  236. 'dont_reset_all');
  237. if(exists $additivity{$name}) {
  238. $logger->additivity($additivity{$name}, 1);
  239. }
  240. for my $appname (@appnames) {
  241. my $appender = create_appender_instance(
  242. $data, $appname, \%appenders_created, \@post_config_subs,
  243. $system_wide_threshold);
  244. $logger->add_appender($appender, 'dont_reset_all');
  245. set_appender_by_name($appname, $appender, \%appenders_created);
  246. }
  247. }
  248. #run post_config subs
  249. for(@post_config_subs) {
  250. $_->();
  251. }
  252. #now we're done, set up all the output methods (e.g. ->debug('...'))
  253. Log::Log4perl::Logger::reset_all_output_methods();
  254. #Run a sanity test on the config not disabled
  255. if($Log::Log4perl::Config::CONFIG_INTEGRITY_CHECK and
  256. !config_is_sane()) {
  257. warn "Log::Log4perl configuration looks suspicious: ",
  258. "$CONFIG_INTEGRITY_ERROR";
  259. }
  260. # Successful init(), save config for later
  261. $OLD_CONFIG = $data;
  262. $Log::Log4perl::Logger::INITIALIZED = 1;
  263. }
  264. ##################################################
  265. sub config_is_sane {
  266. ##################################################
  267. if(! $LOGGERS_DEFINED) {
  268. $CONFIG_INTEGRITY_ERROR = "No loggers defined";
  269. return 0;
  270. }
  271. if(scalar keys %Log::Log4perl::Logger::APPENDER_BY_NAME == 0) {
  272. $CONFIG_INTEGRITY_ERROR = "No appenders defined";
  273. return 0;
  274. }
  275. return 1;
  276. }
  277. ##################################################
  278. sub create_appender_instance {
  279. ##################################################
  280. my($data, $appname, $appenders_created, $post_config_subs,
  281. $system_wide_threshold) = @_;
  282. my $appenderclass = get_appender_by_name(
  283. $data, $appname, $appenders_created);
  284. print "appenderclass=$appenderclass\n" if _INTERNAL_DEBUG;
  285. my $appender;
  286. if (ref $appenderclass) {
  287. $appender = $appenderclass;
  288. } else {
  289. die "ERROR: you didn't tell me how to " .
  290. "implement your appender '$appname'"
  291. unless $appenderclass;
  292. if (Log::Log4perl::JavaMap::translate($appenderclass)){
  293. # It's Java. Try to map
  294. print "Trying to map Java $appname\n" if _INTERNAL_DEBUG;
  295. $appender = Log::Log4perl::JavaMap::get($appname,
  296. $data->{appender}->{$appname});
  297. }else{
  298. # It's Perl
  299. my @params = grep { $_ ne "layout" and
  300. $_ ne "value"
  301. } sort keys %{$data->{appender}->{$appname}};
  302. my %param = ();
  303. foreach my $pname (@params){
  304. #this could be simple value like
  305. #{appender}{myAppender}{file}{value} => 'log.txt'
  306. #or a structure like
  307. #{appender}{myAppender}{login} =>
  308. # { name => {value => 'bob'},
  309. # pwd => {value => 'xxx'},
  310. # }
  311. #in the latter case we send a hashref to the appender
  312. if (exists $data->{appender}{$appname}
  313. {$pname}{value} ) {
  314. $param{$pname} = $data->{appender}{$appname}
  315. {$pname}{value};
  316. }else{
  317. $param{$pname} = {map {$_ => $data->{appender}
  318. {$appname}
  319. {$pname}
  320. {$_}
  321. {value}}
  322. sort keys %{$data->{appender}
  323. {$appname}
  324. {$pname}}
  325. };
  326. }
  327. }
  328. my $depends_on = [];
  329. $appender = Log::Log4perl::Appender->new(
  330. $appenderclass,
  331. name => $appname,
  332. l4p_post_config_subs => $post_config_subs,
  333. l4p_depends_on => $depends_on,
  334. %param,
  335. );
  336. for my $dependency (@$depends_on) {
  337. # If this appender indicates that it needs other appenders
  338. # to exist (e.g. because it's a composite appender that
  339. # relays messages on to its appender-refs) then we're
  340. # creating their instances here. Reason for this is that
  341. # these appenders are not attached to any logger and are
  342. # therefore missed by the config parser which goes through
  343. # the defined loggers and just creates *their* attached
  344. # appenders.
  345. $appender->composite(1);
  346. next if exists $appenders_created->{$appname};
  347. my $app = create_appender_instance($data, $dependency,
  348. $appenders_created,
  349. $post_config_subs);
  350. # If the appender appended a subroutine to $post_config_subs
  351. # (a reference to an array of subroutines)
  352. # here, the configuration parser will later execute this
  353. # method. This is used by a composite appender which needs
  354. # to make sure all of its appender-refs are available when
  355. # all configuration settings are done.
  356. # Smuggle this sub-appender into the hash of known appenders
  357. # without attaching it to any logger directly.
  358. $
  359. Log::Log4perl::Logger::APPENDER_BY_NAME{$dependency} = $app;
  360. }
  361. }
  362. }
  363. add_layout_by_name($data, $appender, $appname) unless
  364. $appender->composite();
  365. # Check for appender thresholds
  366. my $threshold =
  367. $data->{appender}->{$appname}->{Threshold}->{value};
  368. if(defined $system_wide_threshold and
  369. !defined $threshold) {
  370. $threshold = $system_wide_threshold;
  371. }
  372. if(defined $threshold) {
  373. # Need to split into two lines because of CVS
  374. $appender->threshold($
  375. Log::Log4perl::Level::PRIORITY{$threshold});
  376. }
  377. # Check for custom filters attached to the appender
  378. my $filtername =
  379. $data->{appender}->{$appname}->{Filter}->{value};
  380. if(defined $filtername) {
  381. # Need to split into two lines because of CVS
  382. my $filter = Log::Log4perl::Filter::by_name($filtername);
  383. die "Filter $filtername doesn't exist" unless defined $filter;
  384. $appender->filter($filter);
  385. }
  386. if(defined $system_wide_threshold and
  387. defined $threshold and
  388. $
  389. Log::Log4perl::Level::PRIORITY{$system_wide_threshold} >
  390. $
  391. Log::Log4perl::Level::PRIORITY{$threshold}
  392. ) {
  393. $appender->threshold($
  394. Log::Log4perl::Level::PRIORITY{$system_wide_threshold});
  395. }
  396. if(exists $data->{appender}->{$appname}->{threshold}) {
  397. die "invalid keyword 'threshold' - perhaps you meant 'Threshold'?";
  398. }
  399. return $appender;
  400. }
  401. ###########################################
  402. sub add_layout_by_name {
  403. ###########################################
  404. my($data, $appender, $appender_name) = @_;
  405. my $layout_class = $data->{appender}->{$appender_name}->{layout}->{value};
  406. die "Layout not specified for appender $appender_name" unless $layout_class;
  407. $layout_class =~ s/org.apache.log4j./Log::Log4perl::Layout::/;
  408. # Check if we have this layout class
  409. if(!Log::Log4perl::Util::module_available($layout_class)) {
  410. if(Log::Log4perl::Util::module_available(
  411. "Log::Log4perl::Layout::$layout_class")) {
  412. # Someone used the layout shortcut, use the fully qualified
  413. # module name instead.
  414. $layout_class = "Log::Log4perl::Layout::$layout_class";
  415. } else {
  416. die "ERROR: trying to set layout for $appender_name to " .
  417. "'$layout_class' failed";
  418. }
  419. }
  420. eval "require $layout_class" or
  421. die "Require to $layout_class failed ($!)";
  422. $appender->layout($layout_class->new(
  423. $data->{appender}->{$appender_name}->{layout},
  424. ));
  425. }
  426. ###########################################
  427. sub get_appender_by_name {
  428. ###########################################
  429. my($data, $name, $appenders_created) = @_;
  430. if (exists $appenders_created->{$name}) {
  431. return $appenders_created->{$name};
  432. } else {
  433. return $data->{appender}->{$name}->{value};
  434. }
  435. }
  436. ###########################################
  437. sub set_appender_by_name {
  438. ###########################################
  439. # keep track of appenders we've already created
  440. ###########################################
  441. my($appname, $appender, $appenders_created) = @_;
  442. $appenders_created->{$appname} ||= $appender;
  443. }
  444. ##################################################
  445. sub add_global_cspec {
  446. ##################################################
  447. # the config file said
  448. # log4j.PatternLayout.cspec.Z=sub {return $$*2}
  449. ##################################################
  450. my ($letter, $perlcode) = @_;
  451. die "error: only single letters allowed in log4j.PatternLayout.cspec.$letter"
  452. unless ($letter =~ /^[a-zA-Z]$/);
  453. Log::Log4perl::Layout::PatternLayout::add_global_cspec($letter, $perlcode);
  454. }
  455. my $LWP_USER_AGENT;
  456. sub set_LWP_UserAgent
  457. {
  458. $LWP_USER_AGENT = shift;
  459. }
  460. ###########################################
  461. sub config_read {
  462. ###########################################
  463. # Read the lib4j configuration and store the
  464. # values into a nested hash structure.
  465. ###########################################
  466. my($config) = @_;
  467. die "Configuration not defined" unless defined $config;
  468. my @text;
  469. my $parser;
  470. $CONFIG_FILE_READS++; # Count for statistical purposes
  471. my $base_configurator = Log::Log4perl::Config::BaseConfigurator->new(
  472. utf8 => $UTF8,
  473. );
  474. my $data = {};
  475. if (ref($config) eq 'HASH') { # convert the hashref into a list
  476. # of name/value pairs
  477. print "Reading config from hash\n" if _INTERNAL_DEBUG;
  478. @text = ();
  479. for my $key ( sort keys %$config ) {
  480. if( ref( $config->{$key} ) eq "CODE" ) {
  481. $config->{$key} = $config->{$key}->();
  482. }
  483. push @text, $key . '=' . $config->{$key} . "\n";
  484. }
  485. } elsif (ref $config eq 'SCALAR') {
  486. print "Reading config from scalar\n" if _INTERNAL_DEBUG;
  487. @text = split(/\n/,$$config);
  488. } elsif (ref $config eq 'GLOB' or
  489. ref $config eq 'IO::File') {
  490. # If we have a file handle, just call the reader
  491. print "Reading config from file handle\n" if _INTERNAL_DEBUG;
  492. @text = @{ $base_configurator->file_h_read( $config ) };
  493. } elsif (ref $config) {
  494. # Caller provided a config parser object, which already
  495. # knows which file (or DB or whatever) to parse.
  496. print "Reading config from parser object\n" if _INTERNAL_DEBUG;
  497. $data = $config->parse();
  498. return $data;
  499. } elsif ($config =~ m|^ldap://|){
  500. if(! Log::Log4perl::Util::module_available("Net::LDAP")) {
  501. die "Log4perl: missing Net::LDAP needed to parse LDAP urls\n$@\n";
  502. }
  503. require Net::LDAP;
  504. require Log::Log4perl::Config::LDAPConfigurator;
  505. return Log::Log4perl::Config::LDAPConfigurator->new->parse($config);
  506. } else {
  507. if ($config =~ /^(https?|ftp|wais|gopher|file):/){
  508. my ($result, $ua);
  509. die "LWP::UserAgent not available" unless
  510. Log::Log4perl::Util::module_available("LWP::UserAgent");
  511. require LWP::UserAgent;
  512. unless (defined $LWP_USER_AGENT) {
  513. $LWP_USER_AGENT = LWP::UserAgent->new;
  514. # Load proxy settings from environment variables, i.e.:
  515. # http_proxy, ftp_proxy, no_proxy etc (see LWP::UserAgent)
  516. # You need these to go thru firewalls.
  517. $LWP_USER_AGENT->env_proxy;
  518. }
  519. $ua = $LWP_USER_AGENT;
  520. my $req = new HTTP::Request GET => $config;
  521. my $res = $ua->request($req);
  522. if ($res->is_success) {
  523. @text = split(/\n/, $res->content);
  524. } else {
  525. die "Log4perl couln't get $config, ".
  526. $res->message." ";
  527. }
  528. } else {
  529. print "Reading config from file '$config'\n" if _INTERNAL_DEBUG;
  530. print "Reading ", -s $config, " bytes.\n" if _INTERNAL_DEBUG;
  531. # Use the BaseConfigurator's file reader to avoid duplicating
  532. # utf8 handling here.
  533. $base_configurator->file( $config );
  534. @text = @{ $base_configurator->text() };
  535. }
  536. }
  537. print "Reading $config: [@text]\n" if _INTERNAL_DEBUG;
  538. if(! grep /\S/, @text) {
  539. return $data;
  540. }
  541. if ($text[0] =~ /^<\?xml /) {
  542. die "XML::DOM not available" unless
  543. Log::Log4perl::Util::module_available("XML::DOM");
  544. require XML::DOM;
  545. require Log::Log4perl::Config::DOMConfigurator;
  546. XML::DOM->VERSION($Log::Log4perl::DOM_VERSION_REQUIRED);
  547. $parser = Log::Log4perl::Config::DOMConfigurator->new();
  548. $data = $parser->parse(\@text);
  549. } else {
  550. $parser = Log::Log4perl::Config::PropertyConfigurator->new();
  551. $data = $parser->parse(\@text);
  552. }
  553. $data = $parser->parse_post_process( $data, leaf_paths($data) );
  554. return $data;
  555. }
  556. ###########################################
  557. sub unlog4j {
  558. ###########################################
  559. my ($string) = @_;
  560. $string =~ s#^org\.apache\.##;
  561. $string =~ s#^log4j\.##;
  562. $string =~ s#^l4p\.##;
  563. $string =~ s#^log4perl\.##i;
  564. $string =~ s#\.#::#g;
  565. return $string;
  566. }
  567. ############################################################
  568. sub leaf_paths {
  569. ############################################################
  570. # Takes a reference to a hash of hashes structure of
  571. # arbitrary depth, walks the tree and returns a reference
  572. # to an array of all possible leaf paths (each path is an
  573. # array again).
  574. # Example: { a => { b => { c => d }, e => f } } would generate
  575. # [ [a, b, c, d], [a, e, f] ]
  576. ############################################################
  577. my ($root) = @_;
  578. my @stack = ();
  579. my @result = ();
  580. push @stack, [$root, []];
  581. while(@stack) {
  582. my $item = pop @stack;
  583. my($node, $path) = @$item;
  584. if(ref($node) eq "HASH") {
  585. for(sort keys %$node) {
  586. push @stack, [$node->{$_}, [@$path, $_]];
  587. }
  588. } else {
  589. push @result, [@$path, $node];
  590. }
  591. }
  592. return \@result;
  593. }
  594. ###########################################
  595. sub leaf_path_to_hash {
  596. ###########################################
  597. my($leaf_path, $data) = @_;
  598. my $ref = \$data;
  599. for my $part ( @$leaf_path[0..$#$leaf_path-1] ) {
  600. $ref = \$$ref->{ $part };
  601. }
  602. return $ref;
  603. }
  604. ###########################################
  605. sub eval_if_perl {
  606. ###########################################
  607. my($value) = @_;
  608. if(my $cref = compile_if_perl($value)) {
  609. return $cref->();
  610. }
  611. return $value;
  612. }
  613. ###########################################
  614. sub compile_if_perl {
  615. ###########################################
  616. my($value) = @_;
  617. if($value =~ /^\s*sub\s*{/ ) {
  618. my $mask;
  619. unless( Log::Log4perl::Config->allow_code() ) {
  620. die "\$Log::Log4perl::Config->allow_code() setting " .
  621. "prohibits Perl code in config file";
  622. }
  623. if( defined( $mask = Log::Log4perl::Config->allowed_code_ops() ) ) {
  624. return compile_in_safe_cpt($value, $mask );
  625. }
  626. elsif( $mask = Log::Log4perl::Config->allowed_code_ops_convenience_map(
  627. Log::Log4perl::Config->allow_code()
  628. ) ) {
  629. return compile_in_safe_cpt($value, $mask );
  630. }
  631. elsif( Log::Log4perl::Config->allow_code() == 1 ) {
  632. # eval without restriction
  633. my $cref = eval "package main; $value" or
  634. die "Can't evaluate '$value' ($@)";
  635. return $cref;
  636. }
  637. else {
  638. die "Invalid value for \$Log::Log4perl::Config->allow_code(): '".
  639. Log::Log4perl::Config->allow_code() . "'";
  640. }
  641. }
  642. return undef;
  643. }
  644. ###########################################
  645. sub compile_in_safe_cpt {
  646. ###########################################
  647. my($value, $allowed_ops) = @_;
  648. # set up a Safe compartment
  649. require Safe;
  650. my $safe = Safe->new();
  651. $safe->permit_only( @{ $allowed_ops } );
  652. # share things with the compartment
  653. for( sort keys %{ Log::Log4perl::Config->vars_shared_with_safe_compartment() } ) {
  654. my $toshare = Log::Log4perl::Config->vars_shared_with_safe_compartment($_);
  655. $safe->share_from( $_, $toshare )
  656. or die "Can't share @{ $toshare } with Safe compartment";
  657. }
  658. # evaluate with restrictions
  659. my $cref = $safe->reval("package main; $value") or
  660. die "Can't evaluate '$value' in Safe compartment ($@)";
  661. return $cref;
  662. }
  663. ###########################################
  664. sub boolean_to_perlish {
  665. ###########################################
  666. my($value) = @_;
  667. # Translate boolean to perlish
  668. $value = 1 if $value =~ /^true$/i;
  669. $value = 0 if $value =~ /^false$/i;
  670. return $value;
  671. }
  672. ###########################################
  673. sub vars_shared_with_safe_compartment {
  674. ###########################################
  675. my($class, @args) = @_;
  676. # Allow both for ...::Config::foo() and ...::Config->foo()
  677. if(defined $class and $class ne __PACKAGE__) {
  678. unshift @args, $class;
  679. }
  680. # handle different invocation styles
  681. if(@args == 1 && ref $args[0] eq 'HASH' ) {
  682. # replace entire hash of vars
  683. %Log::Log4perl::VARS_SHARED_WITH_SAFE_COMPARTMENT = %{$args[0]};
  684. }
  685. elsif( @args == 1 ) {
  686. # return vars for given package
  687. return $Log::Log4perl::VARS_SHARED_WITH_SAFE_COMPARTMENT{
  688. $args[0]};
  689. }
  690. elsif( @args == 2 ) {
  691. # add/replace package/var pair
  692. $Log::Log4perl::VARS_SHARED_WITH_SAFE_COMPARTMENT{
  693. $args[0]} = $args[1];
  694. }
  695. return wantarray ? %Log::Log4perl::VARS_SHARED_WITH_SAFE_COMPARTMENT
  696. : \%Log::Log4perl::VARS_SHARED_WITH_SAFE_COMPARTMENT;
  697. }
  698. ###########################################
  699. sub allowed_code_ops {
  700. ###########################################
  701. my($class, @args) = @_;
  702. # Allow both for ...::Config::foo() and ...::Config->foo()
  703. if(defined $class and $class ne __PACKAGE__) {
  704. unshift @args, $class;
  705. }
  706. if(@args) {
  707. @Log::Log4perl::ALLOWED_CODE_OPS_IN_CONFIG_FILE = @args;
  708. }
  709. else {
  710. # give back 'undef' instead of an empty arrayref
  711. unless( @Log::Log4perl::ALLOWED_CODE_OPS_IN_CONFIG_FILE ) {
  712. return;
  713. }
  714. }
  715. return wantarray ? @Log::Log4perl::ALLOWED_CODE_OPS_IN_CONFIG_FILE
  716. : \@Log::Log4perl::ALLOWED_CODE_OPS_IN_CONFIG_FILE;
  717. }
  718. ###########################################
  719. sub allowed_code_ops_convenience_map {
  720. ###########################################
  721. my($class, @args) = @_;
  722. # Allow both for ...::Config::foo() and ...::Config->foo()
  723. if(defined $class and $class ne __PACKAGE__) {
  724. unshift @args, $class;
  725. }
  726. # handle different invocation styles
  727. if( @args == 1 && ref $args[0] eq 'HASH' ) {
  728. # replace entire map
  729. %Log::Log4perl::ALLOWED_CODE_OPS = %{$args[0]};
  730. }
  731. elsif( @args == 1 ) {
  732. # return single opcode mask
  733. return $Log::Log4perl::ALLOWED_CODE_OPS{
  734. $args[0]};
  735. }
  736. elsif( @args == 2 ) {
  737. # make sure the mask is an array ref
  738. if( ref $args[1] ne 'ARRAY' ) {
  739. die "invalid mask (not an array ref) for convenience name '$args[0]'";
  740. }
  741. # add name/mask pair
  742. $Log::Log4perl::ALLOWED_CODE_OPS{
  743. $args[0]} = $args[1];
  744. }
  745. return wantarray ? %Log::Log4perl::ALLOWED_CODE_OPS
  746. : \%Log::Log4perl::ALLOWED_CODE_OPS
  747. }
  748. ###########################################
  749. sub allow_code {
  750. ###########################################
  751. my($class, @args) = @_;
  752. # Allow both for ...::Config::foo() and ...::Config->foo()
  753. if(defined $class and $class ne __PACKAGE__) {
  754. unshift @args, $class;
  755. }
  756. if(@args) {
  757. $Log::Log4perl::ALLOW_CODE_IN_CONFIG_FILE =
  758. $args[0];
  759. }
  760. return $Log::Log4perl::ALLOW_CODE_IN_CONFIG_FILE;
  761. }
  762. ################################################
  763. sub var_subst {
  764. ################################################
  765. my($varname, $subst_hash) = @_;
  766. # Throw out blanks
  767. $varname =~ s/\s+//g;
  768. if(exists $subst_hash->{$varname}) {
  769. print "Replacing variable: '$varname' => '$subst_hash->{$varname}'\n"
  770. if _INTERNAL_DEBUG;
  771. return $subst_hash->{$varname};
  772. } elsif(exists $ENV{$varname}) {
  773. print "Replacing ENV variable: '$varname' => '$ENV{$varname}'\n"
  774. if _INTERNAL_DEBUG;
  775. return $ENV{$varname};
  776. }
  777. die "Undefined Variable '$varname'";
  778. }
  779. 1;
  780. __END__
  781. =encoding utf8
  782. =head1 NAME
  783. Log::Log4perl::Config - Log4perl configuration file syntax
  784. =head1 DESCRIPTION
  785. In C<Log::Log4perl>, configuration files are used to describe how the
  786. system's loggers ought to behave.
  787. The format is the same as the one as used for C<log4j>, just with
  788. a few perl-specific extensions, like enabling the C<Bar::Twix>
  789. syntax instead of insisting on the Java-specific C<Bar.Twix>.
  790. Comment lines and blank lines (all whitespace or empty) are ignored.
  791. Comment lines may start with arbitrary whitespace followed by one of:
  792. =over 4
  793. =item # - Common comment delimiter
  794. =item ! - Java .properties file comment delimiter accepted by log4j
  795. =item ; - Common .ini file comment delimiter
  796. =back
  797. Comments at the end of a line are not supported. So if you write
  798. log4perl.appender.A1.filename=error.log #in current dir
  799. you will find your messages in a file called C<error.log #in current dir>.
  800. Also, blanks between syntactical entities are ignored, it doesn't
  801. matter if you write
  802. log4perl.logger.Bar.Twix=WARN,Screen
  803. or
  804. log4perl.logger.Bar.Twix = WARN, Screen
  805. C<Log::Log4perl> will strip the blanks while parsing your input.
  806. Assignments need to be on a single line. However, you can break the
  807. line if you want to by using a continuation character at the end of the
  808. line. Instead of writing
  809. log4perl.appender.A1.layout=Log::Log4perl::Layout::SimpleLayout
  810. you can break the line at any point by putting a backslash at the very (!)
  811. end of the line to be continued:
  812. log4perl.appender.A1.layout=\
  813. Log::Log4perl::Layout::SimpleLayout
  814. Watch out for trailing blanks after the backslash, which would prevent
  815. the line from being properly concatenated.
  816. =head2 Loggers
  817. Loggers are addressed by category:
  818. log4perl.logger.Bar.Twix = WARN, Screen
  819. This sets all loggers under the C<Bar::Twix> hierarchy on priority
  820. C<WARN> and attaches a later-to-be-defined C<Screen> appender to them.
  821. Settings for the root appender (which doesn't have a name) can be
  822. accomplished by simply omitting the name:
  823. log4perl.logger = FATAL, Database, Mailer
  824. This sets the root appender's level to C<FATAL> and also attaches the
  825. later-to-be-defined appenders C<Database> and C<Mailer> to it. Alternatively,
  826. the root logger can be addressed as C<rootLogger>:
  827. log4perl.rootLogger = FATAL, Database, Mailer
  828. The additivity flag of a logger is set or cleared via the
  829. C<additivity> keyword:
  830. log4perl.additivity.Bar.Twix = 0|1
  831. (Note the reversed order of keyword and logger name, resulting
  832. from the dilemma that a logger name could end in C<.additivity>
  833. according to the log4j documentation).
  834. =head2 Appenders and Layouts
  835. Appender names used in Log4perl configuration file
  836. lines need to be resolved later on, in order to
  837. define the appender's properties and its layout. To specify properties
  838. of an appender, just use the C<appender> keyword after the
  839. C<log4perl> intro and the appender's name:
  840. # The Bar::Twix logger and its appender
  841. log4perl.logger.Bar.Twix = DEBUG, A1
  842. log4perl.appender.A1=Log::Log4perl::Appender::File
  843. log4perl.appender.A1.filename=test.log
  844. log4perl.appender.A1.mode=append
  845. log4perl.appender.A1.layout=Log::Log4perl::Layout::SimpleLayout
  846. This sets a priority of C<DEBUG> for loggers in the C<Bar::Twix>
  847. hierarchy and assigns the C<A1> appender to it, which is later on
  848. resolved to be an appender of type C<Log::Log4perl::Appender::File>, simply
  849. appending to a log file. According to the C<Log::Log4perl::Appender::File>
  850. manpage, the C<filename> parameter specifies the name of the log file
  851. and the C<mode> parameter can be set to C<append> or C<write> (the
  852. former will append to the logfile if one with the specified name
  853. already exists while the latter would clobber and overwrite it).
  854. The order of the entries in the configuration file is not important,
  855. C<Log::Log4perl> will read in the entire file first and try to make
  856. sense of the lines after it knows the entire context.
  857. You can very well define all loggers first and then their appenders
  858. (you could even define your appenders first and then your loggers,
  859. but let's not go there):
  860. log4perl.logger.Bar.Twix = DEBUG, A1
  861. log4perl.logger.Bar.Snickers = FATAL, A2
  862. log4perl.appender.A1=Log::Log4perl::Appender::File
  863. log4perl.appender.A1.filename=test.log
  864. log4perl.appender.A1.mode=append
  865. log4perl.appender.A1.layout=Log::Log4perl::Layout::SimpleLayout
  866. log4perl.appender.A2=Log::Log4perl::Appender::Screen
  867. log4perl.appender.A2.stderr=0
  868. log4perl.appender.A2.layout=Log::Log4perl::Layout::PatternLayout
  869. log4perl.appender.A2.layout.ConversionPattern = %d %m %n
  870. Note that you have to specify the full path to the layout class
  871. and that C<ConversionPattern> is the keyword to specify the printf-style
  872. formatting instructions.
  873. =head1 Configuration File Cookbook
  874. Here's some examples of often-used Log4perl configuration files:
  875. =head2 Append to STDERR
  876. log4perl.category.Bar.Twix = WARN, Screen
  877. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  878. log4perl.appender.Screen.layout = \
  879. Log::Log4perl::Layout::PatternLayout
  880. log4perl.appender.Screen.layout.ConversionPattern = %d %m %n
  881. =head2 Append to STDOUT
  882. log4perl.category.Bar.Twix = WARN, Screen
  883. log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  884. log4perl.appender.Screen.stderr = 0
  885. log4perl.appender.Screen.layout = \
  886. Log::Log4perl::Layout::PatternLayout
  887. log4perl.appender.Screen.layout.ConversionPattern = %d %m %n
  888. =head2 Append to a log file
  889. log4perl.logger.Bar.Twix = DEBUG, A1
  890. log4perl.appender.A1=Log::Log4perl::Appender::File
  891. log4perl.appender.A1.filename=test.log
  892. log4perl.appender.A1.mode=append
  893. log4perl.appender.A1.layout = \
  894. Log::Log4perl::Layout::PatternLayout
  895. log4perl.appender.A1.layout.ConversionPattern = %d %m %n
  896. Note that you could even leave out
  897. log4perl.appender.A1.mode=append
  898. and still have the logger append to the logfile by default, although
  899. the C<Log::Log4perl::Appender::File> module does exactly the opposite.
  900. This is due to some nasty trickery C<Log::Log4perl> performs behind
  901. the scenes to make sure that beginner's CGI applications don't clobber
  902. the log file every time they're called.
  903. =head2 Write a log file from scratch
  904. If you loathe the Log::Log4perl's append-by-default strategy, you can
  905. certainly override it:
  906. log4perl.logger.Bar.Twix = DEBUG, A1
  907. log4perl.appender.A1=Log::Log4perl::Appender::File
  908. log4perl.appender.A1.filename=test.log
  909. log4perl.appender.A1.mode=write
  910. log4perl.appender.A1.layout=Log::Log4perl::Layout::SimpleLayout
  911. C<write> is the C<mode> that has C<Log::Log4perl::Appender::File>
  912. explicitly clobber the log file if it exists.
  913. =head2 Configuration files encoded in utf-8
  914. If your configuration file is encoded in utf-8 (which matters if you
  915. e.g. specify utf8-encoded appender filenames in it), then you need to
  916. tell Log4perl before running init():
  917. use Log::Log4perl::Config;
  918. Log::Log4perl::Config->utf( 1 );
  919. Log::Log4perl->init( ... );
  920. This makes sure Log4perl interprets utf8-encoded config files correctly.
  921. This setting might become the default at some point.
  922. =head1 SEE ALSO
  923. Log::Log4perl::Config::PropertyConfigurator
  924. Log::Log4perl::Config::DOMConfigurator
  925. Log::Log4perl::Config::LDAPConfigurator (coming soon!)
  926. =head1 LICENSE
  927. Copyright 2002-2013 by Mike Schilli E<lt>m@perlmeister.comE<gt>
  928. and Kevin Goess E<lt>cpan@goess.orgE<gt>.
  929. This library is free software; you can redistribute it and/or modify
  930. it under the same terms as Perl itself.
  931. =head1 AUTHOR
  932. Please contribute patches to the project on Github:
  933. http://github.com/mschilli/log4perl
  934. Send bug reports or requests for enhancements to the authors via our
  935. MAILING LIST (questions, bug reports, suggestions/patches):
  936. log4perl-devel@lists.sourceforge.net
  937. Authors (please contact them via the list above, not directly):
  938. Mike Schilli <m@perlmeister.com>,
  939. Kevin Goess <cpan@goess.org>
  940. Contributors (in alphabetical order):
  941. Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
  942. Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
  943. Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
  944. Grundman, Paul Harrington, Alexander Hartmaier David Hull,
  945. Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
  946. Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope,
  947. Lars Thegler, David Viner, Mac Yang.