http://www.perlmonks.org?node_id=605366

valdez has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

Log::Log4perl is my preferred tool for logging and this time I want to access some values of its configuration from another application. I've read the documentation, but I didn't find any suitable method; so I started from parsing a configuration file, but very soon I realized that I also needed the variable expansion feature provided by Log4perl; after that I dived into the source and came back with the following class to accomplish the task:

package Log::Log4perl::Config::Standalone; use Log::Log4perl::Config; use Log::Log4perl::Config::PropertyConfigurator; use Carp; sub new { my ($class, $filename) = @_; confess "configuration '$filename' not found\n" unless -f $filename; my $cp = Log::Log4perl::Config::PropertyConfigurator->new; $cp->file( $filename ); my $self = { data => $cp->parse() }; return bless $self, $class; } sub value { my ($self, $path, $default) = @_; my @p = split /\./, $path; shift @p if $p[0] eq 'log4perl'; my $found = 1; my $r = $self->{data}; while (my $n = shift @p) { if (exists $r->{$n}) { $r = $r->{$n}; } else { $found = 0; } } return $found ? $r->{value} : $default; } 1; __END__
Given the following configuration file:
# filename: l4p.conf global_var = /var/log/some/file.log log4perl.rootLogger = DEBUG, LOGFILE log4perl.appender.LOGFILE = Log::Log4perl::Appender::File log4perl.appender.LOGFILE.filename = ${global_var} log4perl.appender.LOGFILE.mode = append log4perl.appender.LOGFILE.layout = PatternLayout log4perl.appender.LOGFILE.layout.ConversionPattern = %d{ISO8601} [%P] +%C %p %m%n
this code retrieves a value:
use Log::Log4perl::Config::Standalone; my $c = Log::Log4perl::Config::Standalone->new('./l4p.conf'); print $c->value('log4perl.appender.LOGFILE.filename'), "\n";
What do you think about it? How would you solve the same problem?

Thanks, Valerio