Reducing dependencies when initializing Log4perl?

R

robb

Hi,

My goal is to have zero dependencies in my source code to artifacts
such as configuration file locations or package names. Usually, the
init code for Log4perl looks like this:

use Log::Log4perl;
Log::Log4perl->init("/path/to/log.conf");
my $logger = Log::Log4perl->get_logger("MyPackage::MySubPackage");

That's just way too much redundant information to put in the top of
each of my source files.

Does anyone have any other solutions? In other words, I believe one
ought to be able to do this:

use MyLogWrapper;
my $logger = MyLogWrapper->get_logger();

Two things would happen here:
1. MyLogWrapper is the only class that knows where the config file is,
and
2. It is able to determine the class/package name for when it invokes
Log4perl->get_logger.

Another option occurred to me, though for #2: I've found that if
Log4perl->get_logger() is invoked without a param, it will determine
the package of the caller. But if this invocation is in a helper class
like this, the helper class's info will be used, not the actual client.

Which made me wonder if late binding would work. In this case, my
wrapper would be used like this:

use MyLogWrapper;
my $logger = MyLogWrapper->get_logger()();

Anyone following me?
 
R

robb

Mumia said:
package MyLogWrapper;
use strict;
use warnings;
use LogForPerl; # Placeholder for Log::Log4perl

BEGIN {
LogForPerl->init('/path/to/log.conf');
}

sub get_logger {
LogForPerl->get_logger('MyPackage::MySubPackage');
}

__END__

But the point is that it should be usable from many packages. And, I
don't want to have code inside a package which hardcodes the package
name... So what I'm looking for, I guess, is code to fill this blank:

sub get_logger {
my $package_name = ... #Code to determine package of caller
LogForPerl->get_logger($package_name);
}
 
R

Randal L. Schwartz

robb@acm> 2. It is able to determine the class/package name for when it invokes Log4perl-> get_logger.

See "perldoc -f caller".
 
R

robb

Randal said:
See "perldoc -f caller".

Thanks! Now I have this, which is working great:

# 1. Figure out the name of the package or script.
my ($package, $filename, $line) = caller;
if ($package eq "main") {
($package) = $filename =~ /([^\/]+)$/;
}

# 2. Configure and retrieve a logger.
return Log::Log4perl->get_logger($package);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top