ave*_*lon 1 perl hook log4perl
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"
Run Code Online (Sandbox Code Playgroud)
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(); }
Run Code Online (Sandbox Code Playgroud)
Where this is the subroutine:
sub av_getLogfileName
{
return $av_std_LOGFILE;
}
Run Code Online (Sandbox Code Playgroud)
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"; }
Run Code Online (Sandbox Code Playgroud)
Is there a way to get result of the variable without the sub inside my script?
print成功时返回 1,所以
sub { print "$av_std_LOGFILE"; }
Run Code Online (Sandbox Code Playgroud)
返回 1,而不是 的值$av_std_LOGFILE。您还必须完全限定 hooks 中的变量名称,这意味着您必须将$av_std_LOGFILE包设为全局。
将你的钩子更改为:
sub { return $main::av_std_LOGFILE; } # double quotes are unnecessary
Run Code Online (Sandbox Code Playgroud)
并在脚本中设置$av_std_LOGFILE如下(在调用之前Log::Log4perl::init):
our $av_std_LOGFILE = '/path/to/logfile';
Run Code Online (Sandbox Code Playgroud)
一般来说,您应该避免全局变量,所以我更喜欢使用子例程。