I would like to use Log4perl inside a package to log messages to a custom filename and to the screen.
My mail file test.pl
:
#!/usr/bin/env perl
use lib '.';
use MyPackage;
helloWorld();
My package file MyPackage.pm
:
package MyPackage;
use Exporter;
our @ISA= qw( Exporter );
our @EXPORT_OK = qw( helloWorld );
our @EXPORT = qw( helloWorld );
sub getLogFileName { return "log.txt"; }
my $log_conf = q(
log4perl.logger = ALL, App, Screen
log4perl.appender.App = Log::Log4perl::Appender::File
log4perl.appender.App.filename = sub { return getLogFileName(); }
log4perl.appender.App.layout = Log::Log4perl::Layout::PatternLayout
log4perl.appender.App.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %p %l %m%n
log4perl.appender.Screen = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.stderr = 0
log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
);
use Log::Log4perl;
Log::Log4perl::init(\$log_conf);
my $logger = Log::Log4perl->get_logger("MyPackage");
sub helloWorld {
$logger->trace('this is a TRACE message');
$logger->debug('this is a DEBUG message');
$logger->info('this is an INFO message');
$logger->warn('this is a WARN message');
$logger->error('this is an ERROR message');
$logger->fatal('this is a FATAL message');
}
1;
Running test.pl
prints out the following error:
Undefined subroutine &main::getLogFileName called at (eval 6) line 1.
Compilation failed in require at ./test.pl line 4.
BEGIN failed--compilation aborted at ./test.pl line 4.
- If I place the same package code inside
test.pl
, it works fine. - If I place a hard-coded filename in
log_conf
insideMyPackage.pm
, it works fine.
Any suggestions on how to fix the error?
CodePudding user response:
sub { return getLogFileName(); }
This subroutine is, based on the error message, evaluated and executed in the scope of the main
package, where there is no getLogFileName()
subroutine. Using a fully qualified name instead like
sub { return MyPackage::getLogFileName(); }
will allow it to call the intended function.