I would like to use a Perl variable from my script in a Log::Log4perl config file. I read the documentation and found that I can use a subroutine, but I would like to do it a little bit simpler, if possible.
I want to set the filename for my appender:
log4perl.appender.av_std_LOGFILE.filename="whateverfilename.log"
But doing this this way, it is a fixed value.
I have the filename in a variable within my script and would like to use this at runtime:
log4perl.appender.av_std_LOGFILE.filename=\
sub { return &av_getLogfileName(); }
Where this is the subroutine:
sub av_getLogfileName
{
return $av_std_LOGFILE;
}
This works, but I would like to avoid the sub inside my script since the return value is very simple.
The documentation says:
Each value starting with the string
sub {...
is interpreted as Perl code to be executed at the time the application parses the configuration...
So I tried something like this, but it did not work:
log4perl.appender.av_std_LOGFILE.filename=\
sub { print "$av_std_LOGFILE"; }
Is there a way to get result of the variable without the sub inside my script?
print
returns 1 on success, so
sub { print "$av_std_LOGFILE"; }
returns 1, not the value of $av_std_LOGFILE
. You also have to fully qualify variable names in hooks, which means you'll have to make $av_std_LOGFILE
a package global.
Change your hook to:
sub { return $main::av_std_LOGFILE; } # double quotes are unnecessary
and set $av_std_LOGFILE
in your script like this (before calling Log::Log4perl::init
):
our $av_std_LOGFILE = '/path/to/logfile';
Generally, you should avoid global variables, so I would prefer using a subroutine.